0

I have a xml file with nodes and attributes

<hotspot name="hs1"/>
<hotspot name="hs2"/>
<hotspot name="hs3"/>

I would like to check if the nodc hotspot exist and if a specific attribute value exist. I'm trying this but id doesn't work...

<?php
$file = 'hotspots.xml';
$xml = simplexml_load_file($file);
$var = $xml->xpath("//hotspot[@name='hs2']");
if (isset($var)) { echo 'does exist' } else {echo 'does not exist'}
?>

Well, it doesn't work at all (error 500) Sorry for being such a newbee, help much appreciated ! THX !

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
jeromebg
  • 19
  • 1
  • 6

1 Answers1

0

Your echo statements should end with a ;

$file = 'hotspots.xml';
$xml = simplexml_load_file($file);
$var = $xml->xpath("//hotspot[@name='hs2']");
if (isset($var)) {
    echo 'does exist';
} else {
    echo 'does not exist';
}

Besides that, the return type of $xml->xpath is an array and when the xpath expression finds no results it will return an empty array.

When it returns an empty array, isset($var) will be true and will give you does exist which is not correct.

One option could be to use count to check if the array contains more than 0 items:

if (count($var) > 0) {

The fourth bird
  • 154,723
  • 16
  • 55
  • 70