我正在尝试在php中将xml转换为json。如果我使用简单的xml和json_encode进行简单的转换,则不会显示xml中的任何属性。
$xml = simplexml_load_file("states.xml");
echo json_encode($xml);
所以我试着像这样手动解析它。
foreach($xml->children() as $state)
{
$states[]= array('state' => $state->name);
}
echo json_encode($states);
状态的输出是{"state":{"0":"Alabama"}}
而不是{"state":"Alabama"}
我做错了什么?
XML:
<?xml version="1.0" ?>
<states>
<state id="AL">
<name>Alabama</name>
</state>
<state id="AK">
<name>Alaska</name>
</state>
</states>
输出:
[{"state":{"0":"Alabama"}},{"state":{"0":"Alaska"}
var转储:
object(SimpleXMLElement)#1 (1) {
["state"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
array(1) {
["id"]=>
string(2) "AL"
}
["name"]=>
string(7) "Alabama"
}
[1]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["id"]=>
string(2) "AK"
}
["name"]=>
string(6) "Alaska"
}
}
}
发布于 2012-01-13 11:56:20
我想通了。json_encode处理对象的方式与字符串不同。我将对象转换为字符串,现在它可以工作了。
foreach($xml->children() as $state)
{
$states[]= array('state' => (string)$state->name);
}
echo json_encode($states);
发布于 2013-10-16 05:36:26
XML中的Json和数组,共3行:
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
发布于 2013-03-11 17:47:25
很抱歉回答了一个老帖子,但这篇文章概述了一种相对简短,简洁和易于维护的方法。我自己测试了一下,效果很好。
http://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/
<?php
class XmlToJson {
public function Parse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
?>
https://stackoverflow.com/questions/8830599
复制相似问题