SimpleXML Reading node with a hyphenated name

后端 未结 2 436
走了就别回头了
走了就别回头了 2020-11-22 12:18

I have the following XML:




        
相关标签:
2条回答
  • 2020-11-22 13:02

    Your assumption is correct. Use

    $officeXML->{'document-meta'}
    

    to make it work.

    Please note that the above applies to Element nodes. Attribute nodes (those within the @attributes property when dumping the SimpleXmlElement) do not require any special syntax to be accessed when hyphenated. They are regularly accessible via array notation, e.g.

    $xml = <<< XML
    <root>
        <hyphenated-element hyphenated-attribute="bar">foo</hyphenated-element>
    </root>
    XML;
    $root = new SimpleXMLElement($xml);
    echo $root->{'hyphenated-element'}; // prints "foo"
    echo $root->{'hyphenated-element'}['hyphenated-attribute']; // prints "bar"
    

    See the SimpleXml Basics in the Manual for further examples.

    0 讨论(0)
  • 2020-11-22 13:16

    I assume the best way to do it is to cast to array:

    Consider the following XML:

    <subscribe hello-world="yolo">
        <callback-url>example url</callback-url>
    </subscribe>
    

    You can access members, including attributes, using a cast:

    <?php
    $xml = (array) simplexml_load_string($input);
    $callback = $xml["callback-url"];
    $attribute = $xml['@attributes']['hello-world'];
    

    It makes everything easier. Hope I helped.

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