$dom ->Call to a member function getAttributeNode() on a non-object

Hi there
I am running a php script here, trying to catch all the anchors from a page. The problem is that most of the anchors are in <li> tag.


$eTagName=$html->getElementsByTagName("li");
foreach ($eTagName as $tagName){
	$value=$tagName->getElementsByTagName("a");
	/*if(!$tagName->hasAttribute("href")){
		echo "element <br />";
		}elseif($tagName->hasAttribute("href")){*/
	$attr=$value->Item(0)->getAttributeNode("href");//attr of a non-object
	$output1=$value->Item(0)->nodeValue;
	$output=$attr->nodeValue;
	echo "Result 2: {$output1}::::::::::::{$output}<br />";
	}

Then i get an error

Call to a member function getAttributeNode() on a non-object

even if i check for existing attrs and achors i get no results.
I believe the error is from this portion of the page


li><span><a href="http://www.gumtree.com/" title="Gumtree">London</a></span></li>

		<li><a href="http://www.gumtree.com/other_gumtrees.html" class="change_city">Change city</a></li>
 <!-- It outputs this tag with attr, and in the next object i get the error -->
	</ul>

</div>

<div id="community_links">



<!--

	<span>Join the Gumtree Community!</span>

-->

	<ul>

		<li class="first" id="community_user"></li>

		<li class="first" id="community_logout"></li>

	</ul>



</div>



So anyway to work around this error with properties like hasAttribute ?

Your problem is that you assume every <li> element contains at least one <a> element. You are assuming it here


$tagName->getElementsByTagName("a");
$attr=$value->Item(0)->getAttributeNode("href");

What if the <li> has no <a> tags as a child? Item(0) won’t exist. You can’t expect to use something that doesn’t exist.

Do you only want to find <a> elements if they’re a child of an <li> tag?
if so


if ($value->length > 0) {
    // there's at least one <a> tag in this <li>, so we can proceed
}

If the <li> may contain more than 1 <a> tag, you better use a loop instead of assuming there’s only one.

If you just want all the <a> tags, and don’t care whther or not they’re a child of an <li>, then ditch the code involving the <li> and just use getElementsByTagName(‘a’)


foreach ($html->getElementsByTagName("a") as $element) {
    // read the attributes
}