Skip to content

Instantly share code, notes, and snippets.

@mchelen
Last active March 1, 2024 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchelen/306f4f31f21c02cb0c24 to your computer and use it in GitHub Desktop.
Save mchelen/306f4f31f21c02cb0c24 to your computer and use it in GitHub Desktop.
PHP SimpleXML Missing Node Test
<?php
/*
ways of checking if simplexml node exists:
isset()
count()
empty()
boolean
tested with PHP 5.5.23
*/
$xml_string = "<?xml version='1.0' encoding='UTF-8'?>
<root>
<note>
<to>Tove</to>
<from>Jani</from>
<content>
<summary>Weekend</summary>
<body>Don't forget me this weekend!</body>
</content>
</note>
</root>";
$xml = simplexml_load_string($xml_string);
$foo = $xml->note;
// isset()
echo PHP_EOL;
if(isset($xml->note->to)) {echo '"to" exists using isset()';}
else {echo '"to" does not exist using isset()';}
echo PHP_EOL;
if(isset($xml->note->bar)) {echo '"bar" exists using isset()';}
else {echo '"bar" does not exist using isset()';}
echo PHP_EOL;
// count()
echo PHP_EOL;
if(count($xml->note->to)>0) {echo '"to" exists using count()';}
else {echo '"to" does not exist using count()';}
echo PHP_EOL;
if(count($xml->note->bar)>0) {echo '"bar" exists using count()';}
else {echo '"bar" does not exist using count()';}
echo PHP_EOL;
// empty()
echo PHP_EOL;
if( !empty($xml->note->to)){echo '"to" exists using empty()';}
else {echo '"to" does not exist using empty()';}
echo PHP_EOL;
if( !empty($xml->note->bar)){echo '"bar" exists using empty()';}
else {echo '"bar" does not exist using empty()';}
echo PHP_EOL;
// boolean
echo PHP_EOL;
if( $xml->note->to){echo '"to" exists using boolean';}
else {echo '"to" does not exist using boolean';}
echo PHP_EOL;
if( $xml->note->bar){echo '"bar" exists using boolean';}
else {echo '"bar" does not exist using boolean';}
echo PHP_EOL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment