hoheckell hoheckell - 4 months ago 46
PHP Question

How get list subItens nodes separateds using PHP DOM

I was seeing this tip
PHP DOM get items from first ul element

But in this case:

<li>First item
First SubItem
Second SubItem

PHP Code:

$DOM = new DOMDocument;
$DOM->loadHTML( $output);
$items = $DOM->getElementsByTagName('ul');

echo '<ul>';
foreach ($items->item(3)->getElementsByTagName('li') as $li) {
echo '<li>'.$li->nodeValue;
$ul = $li->getElementsByTagName('ul');
echo '<ul>';
echo '--->'.$ul->length.'<br>';
foreach ($ul->item($u)->getElementsByTagName('li') as $lii) {
echo '<li>'.$lii->nodeValue.'</li>';
echo '</ul>';
echo '</li>';
echo '</ul>';

The Problem is:
Im getting in //$li->nodeValue;// "First itemFirst SubItemSecond SubItem" as the Fist node;
I need get this items separated (subItems)


I'm assuming you just want to retrieve the text values from those <li> tags.

You can greatly simplify the query with DOMXPath as ->query('//li') will fetch all <li> tags in your code snippet.

$DOM = new DOMDocument();

$xPath = new DOMXPath($DOM);
if($xpResponse = $xPath->query('//li/text()')) {
    echo "<ul>\n";

    foreach($xpResponse as $xNode) {
        echo "<li>" . trim($xNode->nodeValue) . "</li>\n";

    echo "</ul>\n";

This will simply output (as HTML):

  • First item
  • First SubItem
  • Second SubItem