How to check if an element exists with 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 checks.

Is property_exists the right way to find out if there is an artnr element in $ product?

+6
source share
3 answers

The order of the parameters in your code is canceled. First the object is correct, 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 method, this will not work either.

+9
source

I think the arguments are crossed. The first parameter should be a class, the second should be a property ...

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

+3
source

Using:

 function validate_xml_product($product) { $children=$product->children(); foreach($children as $child){ if ($child->getName()=='artnr') { return true; } } return false; } 
+1
source

Source: https://habr.com/ru/post/893943/


All Articles