I am getting the following returned from an api I am working with.. However using SIMPLEXML I am unable to access the values:
<?xml version="1.0" encoding="utf-16"?>
<Response Version="1.0">
<DateTime>2/13/2013 10:37:24 PM</DateTime>
<Contact_ID>151-233-DD</Contact_ID>
<Quote_ID>ojc332-ewied-23e3ed</Quote_ID>
<Status>Failure</Status>
<Reason>Incorrect Contact ID</Reason>
</Response>
I am setting this up with:
$variable = new SimpleXMLElement($results);
SIMPLEXML is giving me the following instead of what I expect to be $variable->DateTime:
SimpleXMLElement Object ( [0] => 2/13/2013 10:37:24 PM 151-233-DD 0jc332-ewied-23e3ed Failure Incorrect Contract ID )
Any help is much appreciated
Seems cause of encoding type utf-16
while content has utf-8
.
So you need to change your encode type,
$string = '<?xml version="1.0" encoding="utf-16"?>
<Response Version="1.0">
<DateTime>2/13/2013 10:37:24 PM</DateTime>
<Contact_ID>151-233-DD</Contact_ID>
<Quote_ID>ojc332-ewied-23e3ed</Quote_ID>
<Status>Failure</Status>
<Reason>Incorrect Contact ID</Reason>
</Response>';
$xml = simplexml_load_string(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $string));
Also It can be done using utf8_encode
,
$xml = simplexml_load_string(utf8_encode($string));
You are constructing only one XML element (hint the name of the class). You need to load the whole string as a XML document. Here is how:
<?php
$result= <<<XML
<?xml version="1.0" encoding="utf-8"?>
<Response Version="1.0">
<DateTime>2/13/2013 10:37:24 PM</DateTime>
<Contact_ID>151-233-DD</Contact_ID>
<Quote_ID>ojc332-ewied-23e3ed</Quote_ID>
<Status>Failure</Status>
<Reason>Incorrect Contact ID</Reason>
</Response>
XML;
$dom= new DOMDocument();
$dom->loadXML($result, LIBXML_NOBLANKS);
Then you can use the DOM interface to access the various components in the document.
eg
$dates = dom->getElementsByTagName('DateTime');
This will fetch an array containing all the DateTime
elements.
EDIT
Oops - $dates
will be an object of DOMNodeList
.
You can then use the various methods to access the nodes and fetch the attributes.
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.