PHP SimpleXML解析问题

2022-04-13 00:00:00 xml php simplexml

我正在使用的API返回以下内容。但是,使用SIMPLEXML我无法访问以下值:

<?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>

我正在设置:

$variable = new SimpleXMLElement($results);
SIMPLEXML为我提供了以下内容,而不是我所期望的 $Variable->日期时间:

SimpleXMLElement Object ( [0] => 2/13/2013 10:37:24 PM 151-233-DD 0jc332-ewied-23e3ed Failure Incorrect Contract ID ) 

非常感谢您的帮助


解决方案

似乎是编码类型utf-16的原因,而内容具有utf-8

因此您需要更改您的编码类型

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

也可以使用utf8_encode

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

相关文章