Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element exists with SimpleXML? [duplicate]

Tags:

php

xml

simplexml

I have the following (simplified XML):

<?xml version="1.0" encoding="UTF-8" ?>

<products>
  <product>
    <artnr>xxx1</artnr>
  </product>
</products>

And the following (again simplified PHP code):

$xml= @simplexml_load_file($filename);

foreach ($xml->product as $product) {
    if (!$this->validate_xml_product($product)) {
        continue;
    }
}

function validate_xml_product($product)
{
    if (!property_exists('artnr', $product)) {
        // why does it always validate to true?
    }
}

For some reason the product never validates.

Isn't property_exists the correct way of finding out whether there is an artnr element in $product?

like image 361
PeeHaa Avatar asked Jul 30 '11 15:07

PeeHaa


2 Answers

The order of parameter in your code is reversed. Correct is first the object then the property-name:

if (!property_exists($product, 'artnr')) {

And apparently this only works for "real" properties. If the property is implemented using the __get-Method this won't work either.

like image 126
vstm Avatar answered Oct 15 '22 01:10

vstm


I think the arguments are crossed. First param should be the class, second the property...

http://php.net/manual/de/function.property-exists.php

like image 3
sthzg Avatar answered Oct 14 '22 23:10

sthzg