Accessing @attribute from SimpleXML

前端 未结 8 1260
后悔当初
后悔当初 2020-11-22 00:33

I am having a problem accessing the @attribute section of my SimpleXML object. When I var_dump the entire object, I get the correct output, and wh

相关标签:
8条回答
  • 2020-11-22 01:08

    Try this

    $xml->attributes()->Token
    
    0 讨论(0)
  • 2020-11-22 01:11

    I used before so many times for getting @attributes like below and it was a little bit longer.

    $att = $xml->attributes();
    echo $att['field'];
    

    It should be more easy and you can get attributes following format only at once:

    Standard Way - Array-Access Attributes (AAA)

    $xml['field'];
    

    Other alternatives are:

    Right & Quick Format

    $xml->attributes()->{'field'};
    

    Wrong Formats

    $xml->attributes()->field;
    $xml->{"@attributes"}->field;
    $xml->attributes('field');
    $xml->attributes()['field'];
    $xml->attributes->['field'];
    
    0 讨论(0)
  • 2020-11-22 01:14

    Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that

     $xml->tagName['attribute']
    

    was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.

    The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.

    Njoy for what its worth (did I mention unique build?).

    0 讨论(0)
  • 2020-11-22 01:19

    If you're looking for a list of these attributes though, XPath will be your friend

    print_r($xml->xpath('@token'));
    
    0 讨论(0)
  • 2020-11-22 01:27
    $xml = <<<XML
    <root>
    <elem attrib="value" />
    </root>
    XML;
    
    $sxml = simplexml_load_string($xml);
    $attrs = $sxml->elem->attributes();
    echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
    

    Use SimpleXMLElement::attributes.

    Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "@attributes", so you can't do $sxml->elem->{"@attributes"}["attrib"].

    0 讨论(0)
  • 2020-11-22 01:28

    You can just do:

    echo $xml['token'];
    
    0 讨论(0)
提交回复
热议问题