简体   繁体   中英

Php Xpath - How to get two information in a child node

How can I get the following information in xpath?

Text 01 - link_1.com

Text 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>';
    }
}

My result is returning

Text 01

Text 02

link_1.com

link_2.com

Text 01

Text 02

link_1.com

link_2.com

Replace // by descendant:: in second and third xpath, because // tells xpath to search this element evrywhere in xml and not in specific node (as you need), and $child is NOT separate XML. descendat:: means any child node

@$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>';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM