如何使用此jQuery表达式查询我的HTML?

时间:2013-04-05 01:47:20

标签: php html dom

我正在处理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编写它?

1 个答案:

答案 0 :(得分:3)

使用XPath:

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

$dataineed = $xp->query('//*[contains(concat(" ",@class," ")," ul ")]//a')
    ->item(0)
    ->getAttribute('href');