【发布时间】:2017-09-15 11:54:40
【问题描述】:
我目前正在尝试使用 php 解析 xml 文档。除了一件事,一切都很顺利。这是我的 xml 示例:
<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,它工作得很好。我只是用 php 遍历每个 <property> 并获取值,例如:
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..."}
这已经差不多了,我只是不知道如何让它正确。
【问题讨论】: