doumengjing1500 2014-12-19 18:34
浏览 350
已采纳

PHP - 使用simplexml_load_string解析XML - 使用CDATA获取空值? [重复]

This question already has an answer here:

When parsing an XML array like:

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <Code>ABC-1001</Code>
    <Brand>ZCOM</Brand>
  </Product>
</Products>

I get an output of:

Array
(
  [0] => Array
  (
    [Code] => AP1024-DDRII640
    [Brand] => ZCOM
  )
}

But when the XML is like:

<?xml version="1.0" encoding="utf-8"?>
<Products Code="ABC-1001">
  <Product>
    <Code><![CDATA[ABC-1001]]></Code>
    <Brand><![CDATA[ZCOM]]></Brand>
  </Product>
</Products>

It returns:

array
  0 => 
    array (size=12)
      '@attributes' => 
        array (size=1)
          'Code' => string 'ABC-1001' (length=8)
      'Code' => 
        array (size=0)
          empty
      'Brand' => 
        array (size=0)
          empty

This is how the XML is parsed from a URL:

$updateUrl = file_get_contents('http://www.someplace/xmlfeed/xml.cfm?asd=12345&uhg=9999');
$updateXml=<<<XML
$updateUrl
XML;
$updateXmlObject=json_decode(json_encode((array) simplexml_load_string($updateXml)), 1);
$updatePHPArray=$updateXmlObject['Product'];

And:

var_dump($updatePHPArray);exit;

Gives the output as above.

Now, why am I getting empty values in the second instance and how could I remedy this without access to the XML source?

</div>
  • 写回答

1条回答 默认 最新

  • duannan4486 2014-12-19 18:47
    关注

    The problem seems to be that the cast you're doing to array can return results different than the actual structure of the XML object.

    Something like the following code should give you an array with the correct info:

    $array = array_map('strval', (array) $xml->Product);
    

    Take care you cast those parts to string of which you'll get the data from (in the example done via strval()). In the opposite, json_encode() is not working well with SimpleXMLElement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?