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

巧了我就是萌 提交于 2019-12-07 03:43:39

问题


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?


回答1:


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.




回答2:


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

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




回答3:


Use:

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


来源:https://stackoverflow.com/questions/6884142/how-to-check-if-element-exists-with-simplexml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!