PHP SimpleXML Parsing Issue

无人久伴 提交于 2019-12-11 06:54:17

问题


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


回答1:


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)); 

Codepad DEMO.

Also It can be done using utf8_encode,

$xml = simplexml_load_string(utf8_encode($string)); 



回答2:


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.

e.g.

$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.



来源:https://stackoverflow.com/questions/14869227/php-simplexml-parsing-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!