1

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!

2
  • Please edit the question to include details of the code you have so far, and the problem you are having, including full text of any error message or unexpected output. Commented Oct 12, 2014 at 13:41
  • Please edit your attempts in your questions. And give the community a clear overview why this didn't work for you and where you are stuck in specific Commented Oct 12, 2014 at 13:41

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

example out

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.