joe joe - 13 days ago 6
PHP Question

Getting into child nodes with php DOMDocument

I know this has been asked a few times before but I really can't seem to figure it out from other examples on here.

$classname = "gallery2";
$pageDOM = new DOMDocument();
$pageDOM->loadHTML($kl);

$xpath = new DOMXPath($pageDOM);
$ul = $xpath->query("//ul[@class='$classname']");
$ulNode = $ul->item(0);

$ulHTML = new DOMDocument();

$ulHTML->appendChild($ulHTML->importNode($ulNode, TRUE));
$ulHTMLsaved = $ulHTML->saveHTML();


var_dump
on $ulHTMLsaved returns all the markup that I want, but then how do I do a foreach and get into to a child node from the existing variable that I've set?

$ulHTMLsaved
contains something like the following & I want to grab various attributes from other nodes nested within all the
li
nodes.

<ul>
<li>
<figure>
<a>
<img src="img.jpg" alt="">
</a>
</figure>
</li>
<li>
<figure>
<a href="">
<img src="img.jpg" alt="">
</a>
</figure>
</li>
</ul>

joe joe
Answer

You can get into child elements by searching for them with the following:

getElementsByTagName

getElementById

There will probably be a more generic one too for classes similar to javascript's querySelectorAll, but not sure what that is currently.

Comments