如何确认/检查XML中是否存在标记

I'm trying to read the XML using DOM parser. My XML is dynamic so I cannot say always all values / tags will present in the XML. In this case i need to check the tag whether it is exists or not before reading it.

I tried like this as well

if($val->getElementsByTagName("cityName") != null) {

}

if(!empty($val->getElementsByTagName("cityName"))) {

}

getting error : Fatal error: Call to a member function getElementsByTagName() on a non-object in F:\xampp\htdocs\test\static-data.php on line 160

Any solution to find the tag existence. As like has Attribute as we check weather Attribute is there or not.

If you use Xpath to fetch the nodes, you can avoid the validation.

Load some XML and create an DOMXpath instance for it.

$xml = <<<XML
<phoneNumbers>
  <phoneNumber type="home">212 555-1234</phoneNumber>
  <phoneNumber type="fax">646 555-4567</phoneNumber>
</phoneNumbers>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

Get the "home" phone number:

var_dump(
  $xpath->evaluate('string(/phoneNumbers/phoneNumber[@type="home"])')
);

Output:

string(12) "212 555-1234"

No "mobile" number exists, so the result is an empty string

var_dump(
  $xpath->evaluate('string(/phoneNumbers/phoneNumber[@type="mobile"])')
);

Output:

string(0) ""

You can count the numbers:

var_dump(
  [
    'all' => $xpath->evaluate('count(/phoneNumbers/phoneNumber)'),
    'home' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="home"])'),
    'fax' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="fax"])'),
    'mobile' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="mobile"])')
  ]
);

Output:

array(4) {
  ["all"]=>
  float(2)
  ["home"]=>
  float(1)
  ["fax"]=>
  float(1)
  ["mobile"]=>
  float(0)
}

Or iterate the numbers

foreach ($xpath->evaluate('/phoneNumbers/phoneNumber') as $phoneNumber) {
  var_dump(
    $phoneNumber->getAttribute('type'),
    $phoneNumber->nodeValue
  );
}

Output:

string(4) "home"
string(12) "212 555-1234"
string(3) "fax"
string(12) "646 555-4567"

Full example: https://eval.in/123212