【问题标题】:How to remove "@attributes" when using simplexml_load_string() to convert XML to JSON使用 simplexml_load_string() 将 XML 转换为 JSON 时如何删除“@attributes”
【发布时间】:2015-09-27 09:05:09
【问题描述】:

我需要的是,

但我得到的是,

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

【问题讨论】:

  • 您是否正在尝试将 xml 字符串转换为 json 对象?如果是,试试这个 $xml = simplexml_load_string($string); $json = json_encode($xml);
  • 我已经转换过了。但结果不是我需要的。
  • 您能介意分享您要转换的 xml 字符串吗?
  • 我也有这个问题:(

标签: php json xml


【解决方案1】:

以下代码适用于我:

// 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);
}

【讨论】:

    【解决方案2】:

    试试这个。它可能对你有用。

    $xml = simplexml_load_string($string); 
    $json = json_encode($xml, true);
    

    【讨论】:

    • 谢谢你的回答,但我得到了相同的结果。 “@attribute”仍然存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2014-06-09
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多