PHP 将 XML 转换为 JSON [英] PHP convert XML to JSON

查看:43
本文介绍了PHP 将 XML 转换为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 xml 转换为 php 中的 json.如果我使用简单的 xml 和 json_encode 进行简单的转换,则 xml 中的任何属性都不会显示.

I am trying to convert xml to json in php. If I do a simple convert using simple xml and json_encode none of the attributes in the xml show.

$xml = simplexml_load_file("states.xml");
echo json_encode($xml);

所以我试图像这样手动解析它.

So I am trying to manually parse it like this.

foreach($xml->children() as $state)
{
    $states[]= array('state' => $state->name); 
}       
echo json_encode($states);

并且 state 的输出是 {"state":{"0":"Alabama"}} 而不是 {"state":"Alabama"}

and the output for state is {"state":{"0":"Alabama"}} rather than {"state":"Alabama"}

我做错了什么?

XML:

<?xml version="1.0" ?>
<states>
    <state id="AL">     
    <name>Alabama</name>
    </state>
    <state id="AK">
        <name>Alaska</name>
    </state>
</states>

输出:

[{"state":{"0":"Alabama"}},{"state":{"0":"Alaska"}

变量转储:

object(SimpleXMLElement)#1 (1) {
["state"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (2) {
  ["@attributes"]=>
  array(1) {
    ["id"]=>
    string(2) "AL"
  }
  ["name"]=>
  string(7) "Alabama"
}
[1]=>
object(SimpleXMLElement)#2 (2) {
  ["@attributes"]=>
  array(1) {
    ["id"]=>
    string(2) "AK"
  }
  ["name"]=>
  string(6) "Alaska"
}
}
}

推荐答案

我想通了.json_encode 处理对象的方式与字符串不同.我将对象转换为字符串,现在可以使用了.

I figured it out. json_encode handles objects differently than strings. I cast the object to a string and it works now.

foreach($xml->children() as $state)
{
    $states[]= array('state' => (string)$state->name); 
}       
echo json_encode($states);

这篇关于PHP 将 XML 转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆