0

我正在处理 HTML,我需要查询它的特定子集,但我只知道如何使用 jQuery 选择器轻松完成此操作。

这是我的 PHP 代码:

$words = array('word');        
$baseUrl = 'http://lema.rae.es/drae/srv/search?val='; //word goes at the end        
$resultIndex = 0;

foreach($words as $word) {
    if (!isset($_REQUEST[$word]))
        continue;
    $contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));

    // THIS DOESN'T WORK! HOW DO I WRITE THIS IN PHP
    $dataineed = $contents.find(".ul a").attr("href"); 

    $contents = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/',     $contents);

    echo "<div id='results' style='
      //style
     ", (++$resultIndex) ,"'>", $dataineed, $contents,
        "</div>";
}

我将在 jQuery 中使用的查询是这样的:

.find(".ul a").attr("href")

如何使用 PHP 和 DOM 编写它?

4

1 回答 1

3

使用 XPath:

$doc = new DOMDocument();
$doc->loadHTML($contents);
$xp = new DOMXPath($doc);

$dataineed = $xp->query('//*[contains(concat(" ",@class," ")," ul ")]//a')
    ->item(0)
    ->getAttribute('href');
于 2013-04-05T01:52:20.000 回答