我很难使用以 xml 作为响应的 api。我使用 simplexml_load_string() 将 xml 转换为 php 对象,然后使用 json_encode() 转换为 json 响应。当所有元素都填充如下时
<content>
<row>
<column>
<item1>Item 1</item1>
<item2>Item 2</item2>
</column>
</row>
<row>
<column>
<item1>Item 1</item1>
<item2>Item 2</item2>
</column>
</row>
</content>
json 响应将是正确的,如下所示
{
"content": {
"row": [
{
"column": [
{
"item1": "Item 1",
"item2": "Item 2"
},
{
"item1": "Item 1",
"item2": "Item 2"
}
]
},
{
"column": [
{
"item1": "Item 1",
"item2": "Item 2"
},
{
"item1": "Item 1",
"item2": "Item 2"
}
]
}
]
}
}
但是,当存在空项目时,相应 xml 的 json 响应将有所不同,从而破坏我的 api。
<content>
<row>
<column>
<item1></item1>
<item2></item2>
</column>
</row>
<row>
<column>
<item1>Item 1</item1>
<item2>Item 2</item2>
</column>
</row>
</content>
对于上面的 xml json 响应将是
{
"row":[
{
"column":[
{
"item1":{
},
"item2":{
}
},
{
"item1":"Item 1",
"item2":"Item 2"
}
]
},
{
"column":[
{
"item1":"Item 1",
"item2":"Item 2"
},
{
"item1":"Item 1",
"item2":"Item 2"
}
]
}
]
}
与上一个不同。请问有什么办法可以解决这个问题吗?
最佳答案
使用xpath()
获取空节点并使用unset()
删除它们
工作示例:
$xml_string = <<<XML
<content>
<row>
<column>
<item1></item1>
<item2></item2>
</column>
</row>
<row>
<column>
<item1>Item 1</item1>
<item2>Item 2</item2>
</column>
</row>
</content>
XML;
$xml = simplexml_load_string($xml_string);
$xpath = '//*[not(normalize-space())]';
foreach (array_reverse($xml->xpath($xpath)) as $remove) {
unset($remove[0]);
}
$json = json_encode($xml);
echo $json;
关于php - simplexml_load_string() 将空 xml 元素转换为对象而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43813044/