How to Check if an XML Node Exists Using PHP SimpleXML?

Check if a node exists in an XML document using PHP SimpleXML

To check if a node exists when traversing an XML document using SimpleXML in PHP, you can simply use the isset() function.

For example, let's suppose you have the following XML document:

$xmlStr =<<<XML
<?xml version="1.0"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://www.designcise.com</loc>
    </url>
    <url>
        <loc>https://designcise.com/web/develop/category/backend/php</loc>
    </url>
</urlset>
XML;

To check if a specific node exists in this XML document, you can use isset(), for example, like so:

$xml = new SimpleXMLElement($xmlStr);

var_dump(isset($xml->url)); // true
var_dump(isset($xml->nonExistent)); // false

var_dump(isset($xml->url->loc)); // true
var_dump(isset($xml->url->nonExistent)); // false

var_dump(isset($xml->url[0]->loc)); // true
var_dump(isset($xml->url[1]->loc)); // true
var_dump(isset($xml->url[2]->loc)); // false

You may also use the nullsafe operator (?->) or the null coalescing operator (??) to access XML nodes (that may potentially not exist) in a safe way (i.e. without the script throwing errors).


Hope you found this post useful. It was published . Please show your love and support by sharing this post.