• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 456
  • Last Modified:

checking for xml tag name exists in PHP

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

Open in new window

1 Solution
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).

$xmlstring = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<body>Don't forget me this weekend!</body>

$xml = simplexml_load_string($xmlstring);

if ( isset ( $xml->from ))
  echo "from = $xml->from" . PHP_EOL;
  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.
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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now