【发布时间】:2015-02-18 17:43:24
【问题描述】:
当解析 XML 数组时:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<Code>ABC-1001</Code>
<Brand>ZCOM</Brand>
</Product>
</Products>
我得到以下输出:
Array
(
[0] => Array
(
[Code] => AP1024-DDRII640
[Brand] => ZCOM
)
}
但是当XML是这样的:
<?xml version="1.0" encoding="utf-8"?>
<Products Code="ABC-1001">
<Product>
<Code><![CDATA[ABC-1001]]></Code>
<Brand><![CDATA[ZCOM]]></Brand>
</Product>
</Products>
返回:
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
这是从 URL 解析 XML 的方式:
$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'];
还有:
var_dump($updatePHPArray);exit;
如上给出输出。
现在,为什么我在第二个实例中得到空值?如果不访问 XML 源,我该如何解决这个问题?
【问题讨论】:
-
获取一个字符串究竟有什么意义,使用heredoc将该字符串填充到另一个字符串中,然后将第二个字符串填充到xml中,强制它到一个数组中。 json_encoding,json_decoding?那只是完全的货物崇拜节目。
-
@MarcB 我是菜鸟...这是我能想到的最好的。对任何更好的解决方案持开放态度,嘿:)
-
SimpleXML with cdata -> stackoverflow.com/questions/2970602/…
-
好吧,既然正在进行一些规范化,那就没关系了。但仅用于原始转换:
$xml = simplexml_load_file('http:/...');可以。 -
通过使用
json_decode(json_encode())hack,您同时抛弃了SimpleXML 的所有功能,并为自己引入了一大堆不必要的问题。simplexml_load_string/simplexml_load_file的结果是一个拥有很多有用魔力的物体,不要一有机会就扔掉它。