php - 使用 simplexml_load_string() 将 XML 转换为 JSON 时如何删除 "@attributes"

标签 php json xml

我需要的是,

enter image description here

但我得到的是,

enter image description here

如何从结果中删除“@attributes”。

最佳答案

下面的代码对我有用:

// Cleans up ugly JSON data by removing @attributes tag
function cleanup_json ($ugly_json) {
   if (is_object($ugly_json)) {
      $nice_json = new stdClass();
      foreach ($ugly_json as $attr => $value) {
         if ($attr == '@attributes') {
            foreach ($value as $xattr => $xvalue) {
              $nice_json->$xattr = $xvalue;
            }
         } else {
            $nice_json->$attr = cleanup_json($value);
         }
      }
      return $nice_json;
   } else if (is_array($ugly_json)) {
      $nice_json = array();
      foreach ($ugly_json as $n => $e) {
        $nice_json[$n] = cleanup_json($e);
      }
      return $nice_json;
   } else {
      return $ugly_json;
   }
}

// Convert XML to JSON
function convert_to_json ($xml_string) {
   $xml = simplexml_load_string($xml_string);
   $ugly_json = json_decode(json_encode($xml));
   $nice_json = cleanup_json($ugly_json);
   return json_encode($nice_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}

关于php - 使用 simplexml_load_string() 将 XML 转换为 JSON 时如何删除 "@attributes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309863/

相关文章:

javascript - strope.js 和 openfire 谁在页面重新加载时终止连接?

javascript - js删除提交的表单数据

javascript - 从 javascript(调用 API)返回包含对象(__proto__)的错误 json

c# - 如何使用 XmlReader 读取 json

PHP 舍入为整数

php - 显示 IP 地址的一部分

php - 使用 INSERT 和 WHERE 进行 MySQLi 查询,可能吗?

java - 将 xml 转换为 json 而不转换字符串/整数?

java - 我可以使用 JAXB 将所有 namespace 定义放入顶级元素吗

c# - 使用反射将 XML 转换为对象