我目前正在嘗試用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很樂意幫助你的朋友... :) –