checking for xml tag name exists in PHP

I want to check if certain tags exist in xml
example:
$data = $xmlString;
$xml = simplexml_load_string($data);
//  does $xml->xxxName exist the do something
$customerName = $xml->xxxName;

Open in new window

prowebinteractiveincAsked:
Who is Participating?
 
Hugh McCurdyCommented:
"Certain tag" is a big vague but if the name of the tag is know ahead of time, you could do something like this (borrowed and then modified from W3schools).

<?php
$xmlstring = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;

$xml = simplexml_load_string($xmlstring);

if ( isset ( $xml->from ))
  echo "from = $xml->from" . PHP_EOL;
else
  echo "from isn't set" . PHP_EOL;
?> 

Open in new window


I showed that for illustration (and also because I can debug that example).

Here's what you want, assuming the tag is called name.

$data = $xmlString;
$xml = simplexml_load_string($data);
if ( isset ( xml->xxxName ))
  $customerName = $xml->xxxName;

Open in new window


If that doesn't work, I'll need a better understanding of what you are trying to accomplish.
~Hugh
0
 
Ray PaseurCommented:
If this is a follow-on from your earlier question that had invalid XML, you would want to start by loading the XML, then testing to see if the object existed or if the SimpleXML_Load_xxx() returned FALSE. Just a thought... ~Ray
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.