2

如何在 xpath 中获取以下信息?

文本 01 - link_1.com

文本 02 - link_2.com

$page = '
<div class="news">
<div class="content">
    <div>
    <span class="title">Text 01</span>
    <span class="link">link_1.com</span>
    </div>
</div>
<div class="content">
    <div>
    <span class="title">Text 02</span>
    <span class="link">link_2.com</span>
    </div>
</div>
</div>';
@$this->dom->loadHTML($page);
$xpath = new DOMXPath($this->dom);

// perform step #1
$childElements = $xpath->query("//*[@class='content']");
$lista = '';
foreach ($childElements as $child) {
    // perform step #2
    $textChildren = $xpath->query("//*[@class='title']", $child);
    foreach ($textChildren as $n) {
        echo $n->nodeValue.'<br>';
    }

    $linkChildren = $xpath->query("//*[@class='link']", $child);
    foreach ($linkChildren as $n) {
        echo $n->nodeValue.'<br>';
    }
}

我的结果正在返回

文字 01

文字 02

链接_1.com

链接_2.com

文字 01

文字 02

链接_1.com

链接_2.com

4

1 回答 1

10

在第二个和第三个 xpath 中替换//descendant::,因为//告诉 xpath 在 xml 中的任何位置而不是在特定节点中搜索此元素(根据您的需要),并且 $child 不是单独的 XML。descendat::表示任何子节点

@$this->dom->loadHTML($page);
$xpath = new DOMXPath($this->dom);

// perform step #1
$childElements = $xpath->query("//*[@class='content']");
$lista = '';
foreach ($childElements as $child) {
    // perform step #2
    $textChildren = $xpath->query("descendant::*[@class='title']", $child);
    foreach ($textChildren as $n) {
        echo $n->nodeValue.'<br>';
    }

    $linkChildren = $xpath->query("descendant::*[@class='link']", $child);
    foreach ($linkChildren as $n) {
        echo $n->nodeValue.'<br>';
    }
}
于 2012-07-13T13:58:02.690 回答