tags:

views:

185

answers:

2

How do i check if a TAGname exists inside an XML file.

so if i want to get

$dom->getElementsByTagName('error')

and it doesn't exist, it prints out something like an error message.

EDIT:

I'm working from an API. So what happens is when a user enters an incorrect username, another XML files is loaded that contains the tag <error>.

However, if they enter the correct username, the XML file doesn't contain the <error> tag so I'm looking for a way to check if the error tag exists inside an XML.

Thanks

+3  A: 
$dom = new DOMDocument(); 
$dom->load( 'some.xml' ); 

$errorNodes = $dom->getElementsByTagName('error'); 

if($errorNodes->length == 0)
{
  message('no error nodes'); // user defined
}
Ewan Todd
This works fine, but if the XML that is loaded doesn't contain the <error> tag(which means it works), it still displays the message.
Stephen
Huh! I don't know for sure what is going on without seeing your code and data. What I do know is that DOMDocument is not very tolerant of ill formed XML (which is easy to make). I would expect DOMDocument to choke pretty badly if it consumed some bad XML, but if not it might show an $errorNodes->length of zero for XML that contained an error tag. You could try printing out the DOMDocument to see if it's worth testing to see that the XML loaded properly.
Ewan Todd
A: 
$errors = $dom->getElementsByTagName('error');
$exists = $errors->length > 0;

if (!$exists ) {
    echo 'Error message..';
}
meder