我尝试不使用json_encode / json_decode将XML转换为JSON。我有以下代码,请记住,我是PHP和JSON的新手。
<?php
$myXMLData =
"<test>
<info>
<sample>
<sampleOne>test</sampleOne>
<sampleTwo>test two</sampleTwo>
<values value='today'>
<sampleThree>test three</sampleThree>
<sampleFour>test four</sampleFour>
<sampleFive>
<sampleSix>test six</sampleSix>
</sampleFive>
</values>
</sample>
</info>
</test>";
$contents=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
//print_r($contents);
echo '{"' . $contents->getName() . '":{"';
foreach ($contents->children() as $child1)
{
$child1->count();
echo $child1->getName() . '": {"';
echo $child1->attributes();
echo $child1[0];
foreach ($child1->children() as $child2)
{
$child2->count();
echo $child2->getName() . '": {"';
echo $child2->attributes();
echo $child2[0] . ": ";
foreach ($child2->children() as $child3)
{
$child3->count();
echo $child3->getName() . '": {"';
echo $child3->attributes();
echo $child3[0];
foreach ($child3->children() as $child4)
{
$child4->count();
echo $child4->getName();
echo $child4->attributes();
echo $child4[0];
foreach ($child4->children() as $child5)
{
echo $child5->getName();
echo $child5->attributes();
echo $child5[0];
}
}
}
}
}
echo "}";
?>
结果应该看起来像一个JSON文件,但是我被困在这里。
{
"test": {
"info": {
"sample": {
"sampleOne": "test",
"sampleTwo": "test two",
"values": {
"-value": "today",
"sampleThree": "test three",
"sampleFour": "test four",
"sampleFive": { "sampleSix": "test six" }
}
}
}
}
}
我不确定这是否是一个好方法。但是我已经花了几个小时来解决这个问题。
答案 0 :(得分:1)
正如评论中所提到的,递归是解决问题的方法。基本上,您需要一个函数,该函数获取SimpleXMLElement作为参数,并以每个子级作为参数递归调用自身。这应该使您了解如何执行此操作(尽管没有属性处理,也没有多个孩子的逗号):
$masterNode = simplexml_load_string($string);
convertNodeToJSON($masterNode);
function convertNodeToJSON($node) {
if ($node->count === 0) { // the current node is text
echo '"' . $node->getName() . '"';
return;
}
echo '{ "' . $node->getName() . '" : ';
foreach ($node->attributes as $attr) {
// handle attributes
}
foreach ($node->children() as $child) {
convertNodeToJSON($child);
// add a comma if necessary
}
echo "}";
}
该代码未经测试,但是无论如何它仅仅是一个起点。希望这会有所帮助:)