简体   繁体   中英

How to convert an XML string into a DOMDocument in PHP?

I got an example XML string from a customer, which I would like to transform to a DOMDocument. I can't seem to get the first node right though....

The string looks like this;

<ev:Events xmlns:ev="xsdEvents" xsi:schemaLocation="xsdEvents [url]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Node>
        <OtherNode>value</OtherNode>
    </Node>
</ev:Events>

How would I set this up the proper way via DOMDocument in PHP?

Well, loading a XML string to a DOMDocument object is not quite that hard -- you'll just have to use DOMDocument::loadXML() .

For example, in your case, you'd use :

$string = <<<XML
<ev:Events xmlns:ev="xsdEvents" xsi:schemaLocation="xsdEvents [url]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Node>
        <OtherNode>value</OtherNode>
    </Node>
</ev:Events>
XML;

$dom = new DOMDocument();
$dom->loadXML($string);


Then, accessing your data is just a matter of using the relevant DOM methods.

For example, to extract the value of your <OtherNode> node, you could use :

$items = $dom->getElementsByTagName('OtherNode');
if ($items->length > 0) {
  var_dump( $items->item(0)->nodeValue );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM