我目前正在尝试用php解析xml文档。除了一件事之外,一切都进展顺利。以下是我的xml示例:从PHP的部分XML创建JSON
<properties>
<property>
<propertyid>1</propertyid>
<flags>
<flag>This is a flag</flag>
<flag>This is another flag</flag>
<flag>This is yet another flag</flag>
<flag>etc...</flag>
</flags>
</property>
<property>
...
</property>
<properties>
正如您所见,有多个<property>
节点。我使用SimpleXML,它工作得很好。我只是通过每个<property>
用PHP循环,得到的值,例如:
foreach ($xml->$property as $property)
{
echo $property->propertyid;
}
的问题是<flag>
节点。基本上,我想结束与看起来像这样的JSON:
{
"flags1":
{
"flag": "This is a flag"
},
"flags2":
{
"flag": "This is another flag"
},
"flags3":
{
"flag": "This is yet another flag"
}
,
"flags4":
{
"flag": "..."
}
}
每个属性将有不确定数量的标志。我已经尝试了一个foreach循环来获取标志值的工作,但那么我怎么能得到值看起来像示例JSON?
我foreach循环是这样的:
$flags = $property->flags;
foreach ($flags->flag as $index => $flag)
{
$arr = array($index => (string)$flag);
echo json_encode($arr);
}
将返回:
{"flag":"This is a flag"}{"flag":"This is another flag"}{"flag":"This is yet another flag"}{"flag":"etc..."}
这等近那里,我只是不知道如何得到它是正确的。
谢谢你,这是完美的:) – DesignSubway
@DesignSubway很乐意帮助你的朋友... :) –