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).
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.