简体   繁体   中英

use DOMXPath and function query php

Have the following html code section:

<ul id="tree">
  <li>
    <a href="">first</a>
    <ul>
      <li><a href="">subfirst</a></li>
      <li><a href="">subsecond</a></li>
      <li><a href="">subthird</a></li>
    </ul>
  </li>
  <li>
    <a href="">second</a>
    <ul>
      <li><a href="">subfirst</a></li>
      <li><a href="">subsecond</a></li>
      <li><a href="">subthird</a></li>
    </ul>
  </li>
</ul>

Need parse this html code and get next (using DOMXPath::query() and foreach())

- first
-- subfirst
-- subsecond
-- subthird
- second
-- subfirst
-- subsecond
-- subthird

Piece of code:

$xpath = new \DOMXPath($html);
$catgs = $xpath->query('//*[@id="tree"]/li/a');
foreach ($catgs as $category) {
  // first level
  echo '- ' . mb_strtolower($category->nodeValue) . '<br>';

  // second level
  // don't know
} 

Thanks in advance!

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.

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

example out

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