php SimpleXML attributes are missing

前端 未结 2 2002
逝去的感伤
逝去的感伤 2020-11-29 13:27

I have the following xml document here: Edit: (see below for sample)

I am using php/SimpleXML to covert it to an object to read it:

$xmlContent = fil         


        
相关标签:
2条回答
  • 2020-11-29 13:55

    The simple answer here is not to use print_r() with SimpleXML objects. Because they are wrappers around non-PHP data, functions like that which would normally show the "whole" object don't really reflect what you're looking at.

    The way to access an attribute with SimpleXML is to use the attribute name as though it was an array key ($node['attribute']); this does not mean that there is an array somewhere with that key, it is a function-call in disguise.

    If you want to get a feel for which nodes you're looking at while writing SimpleXML code, check out this simplexml_dump() function which I wrote (feedback welcome).

    0 讨论(0)
  • 2020-11-29 14:02

    First, you have to get the SimpleXMLElement object. In this case:

    $xmlContent = file_get_contents($path . '/test.xml');
    $tablesRaw = new SimpleXMLElement($xmlContent);
    $elements = $tablesRaw->table[22]->fields->field[31]->{'acceptable-values'}->children();
    

    Now, you can iterate over each acceptable-value object and use the attributes() method:

    foreach($elements as $element) {
        echo $element->attributes()->value . " ";
        echo trim($element[0]) . "\n";
    }
    

    With your XML, that will print:

    0 Unknown
    1 Invalid
    2 Deleted
    3 Valid/Good
    4 Inactive
    

    It doesn't rely on the array index, because the call to attributes() gets the actual attributes of the element. And ->value gets the attribute with the name "value".

    0 讨论(0)
提交回复
热议问题