Use DOMXPath And Function Query Php
Solution 1:
This is what DOMBLAZE is for:
/* DOMBLAZE */ $doc->registerNodeClass("DOMElement","DOMBLAZE"); class DOMBLAZE extends DOMElement{public function __invoke($expression) {return $this->xpath($expression);} function xpath($expression){$result=(new DOMXPath($this->ownerDocument))->evaluate($expression,$this);return($result instanceof DOMNodeList)?new IteratorIterator($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($elements as $el) {
$head = $xpath->query('./a', $el)->item(0)->nodeValue;
echo "- $head <br/>";
foreach($xpath->query('./ul/li/a', $el) as $sub) { // query the second level
echo '-- ' . $sub->nodeValue . '<br/>';
}
}
Post a Comment for "Use DOMXPath And Function Query Php"