2012-07-13 68 views
1

如何在xpath中獲取以下信息?Php 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

link_1.com

link_2.com

文本01

文本02

link_1.com

link_2.com

回答

4

在第二和第三的XPath descendant::更換//,因爲//告訴XPath來在xml中搜索此元素evrywhere而不是在特定節點中(如您所需),並且$ 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>'; 
    } 
} 
+0

謝謝。有效 – adrianogf 2012-07-13 14:50:25

相關問題