php - simplexml_load_string() 将空 xml 元素转换为对象而不是字符串

标签 php xml simplexml

我很难使用以 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/

相关文章:

c# - 在没有单独方法的情况下在 RESTful WCF 中混合 XML 和 JSON

xml - 有没有办法在 schematron 中传递变量?

php - 如何在带有嵌套数组和对象的 php 中使用递归函数?

php - 将推文发布到用户帐户

php - 读取图像 block : Fatal Error when converting SVG into PNG

php - PHP 中的无效代码或消息

php - XPath 无效表达式

php - 使用 grep 在目录中的所有文件中搜索字符串的实例,使用 PHP bash 脚本

java - 如何将JSON转换为指定的XML格式

php - 使用 PHP 将 XML 结构插入为另一个 XML 元素的子元素