如何使用xPath获取此标记内的数据?

时间:2013-11-06 20:42:55

标签: php xpath

使用xPath,如何获取此标记内的数据?

<a href="/poker/?ca=v"> THIS </a>

这是源代码,我不知道是否需要获取树

<div id="nav">
        <ul id="someID">
            <li><a href="/poker/?ca=v"> THIS </a></li>
        </ul>
</div>

谢谢

更新

这是我的代码

function extractNodeValue($query, $xPath, $attribute = null) {
    $node = $xPath->query("//{$query}")->item(0);
    if (!$node) {
        return null;
    }
    return $attribute ? $node->getAttribute($attribute) : $node->nodeValue;
}

$document = new DOMDocument();
$document->loadHTML($html);
$xPath = new DOMXpath($document);
$name = extractNodeValue('//*[@id="row1"]',$xPath);

echo $name;

1 个答案:

答案 0 :(得分:0)

查询:

//a[href="/poker/?ca=v"]/text()

PHP:

$html = <<<EOF
  ... the html (can be even a snippet)...
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXPath($doc);
$query = '//a[href="/poker/?ca=v"]/text()';

foreach($selector->query($query) as $text) {
    echo $text->nodeValue;
}