Use Domxpath And Function Query Php
Solution 1:
This is what DOMBLAZE is for:
/* DOMBLAZE */$doc->registerNodeClass("DOMElement","DOMBLAZE"); classDOMBLAZEextendsDOMElement{publicfunction__invoke($expression) {return$this->xpath($expression);} functionxpath($expression){$result=(new DOMXPath($this->ownerDocument))->evaluate($expression,$this);return($resultinstanceof DOMNodeList)?newIteratorIterator($result):$result;}}
$list = $doc->getElementById('tree');
foreach ($list('./li') as$item) {
echo'- ', $item('string(./a)'), "\n";
foreach ($item('./ul/li') as$subitem) {
echo'-- ', $subitem('string(./a)'), "\n";
}
}
Output:
- first-- subfirst-- subsecond-- subthird- second-- subfirst-- subsecond-- subthird
DOMBLAZE is FluentDOM for the poor.
Solution 2:
For the second level, you could use another query also:
$dom = new DOMDocument();
$dom->loadHTML($markup);
$xpath = new DOMXpath($dom);
$elements = $xpath->query('//ul[@id="tree"]/li');
foreach($elementsas$el) {
$head = $xpath->query('./a', $el)->item(0)->nodeValue;
echo"- $head <br/>";
foreach($xpath->query('./ul/li/a', $el) as$sub) { // query the second levelecho'-- ' . $sub->nodeValue . '<br/>';
}
}
Post a Comment for "Use Domxpath And Function Query Php"