当有一个孩子时,PHP将XML转换为JSON组 [英] PHP convert XML to JSON group when there is one child

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

问题描述

我使用此PHP类将XML转换为JSON: http://www. ibm.com/developerworks/library/x-xml2jsonphp/

I use this PHP class to convert XML to JSON:http://www.ibm.com/developerworks/library/x-xml2jsonphp/

例如此XML:

<?xml version="1.0" encoding="UTF-8"?>
<searchResult>
    <status>OK</status>
    <users>
        <user>
            <userName>johndoe</userName>
        </user>
        <user>
            <userName>johndoe1</userName>
            <fullName>John Doe</fullName>
        </user>
        <user>
            <userName>johndoe2</userName>
        </user>
        <user>
            <userName>johndoe3</userName>
            <fullName>John Doe Mother</fullName>
        </user>
        <user>
            <userName>johndoe4</userName>
        </user>
    </users>
</searchResult>

结果是:

{
  "searchResult": {
    "status": "OK",
    "users": {
      "user": [
        { "userName": "johndoe" },
        {
          "userName": "johndoe1",
          "fullName": "John Doe"
        },
        { "userName": "johndoe2" },
        {
          "userName": "johndoe3",
          "fullName": "John Doe Mother"
        },
        { "userName": "johndoe4" }
      ]
    }
  }
}

但是我想要:

{
  "searchResult": {
    "status": "OK",
    "users": [
      { "userName": "johndoe" },
      {
        "userName": "johndoe1",
        "fullName": "John Doe"
      },
      { "userName": "johndoe2" },
      {
        "userName": "johndoe3",
        "fullName": "John Doe Mother"
      },
      { "userName": "johndoe4" }
    ]
  }
}

在用户"中将用户"分组,因为这是一个只有一个孩子的数组.

Grouping "user" in "users", because this is an array with just one child.

我已经搜索了另一个类以将XML转换为JSON以得到此结果,但是我没有找到任何资源.

I've search another class to convert XML to JSON to have this result but i've not find any ressources.

能帮我解决我的问题吗?

Can you please help me to solve my problem.

在此先感谢Fabrice

Thanks in advance, best regards Fabrice

推荐答案

您链接的文章已经过时了.例如,通常不再需要 Services_JSON . .

The article you've linked is pretty outdated. For example Services_JSON is normally not needed any longer.

稳定的PHP 5.4版本现在具有 json_encode()函数 iterator_to_array .即使您使用的是旧版PHP 5.3,以下示例也很容易采用.

The stable PHP 5.4 version right now has json_encode() function and the JsonSerializable interface as well as iterator_to_array. Even if you're using the older PHP 5.3 version, the following example is pretty easy to adopt.

因此,您真正需要的是您自己的SimpleXMLElement JSON编码.

So what you actually need is your own JSON encoding of a SimpleXMLElement.

首先,让我们创建我们自己的" Json编码器:

So first of all, let's just create "our own" Json encoder:

class XML2Json extends SimpleXMLElement
{
}

哇.那简直太简单了.让我们检查一下它是否有效:

Wow. That was dead simple. Let's check that it works:

$converter = new XML2Json($bufferXml);

echo json_encode($converter, JSON_PRETTY_PRINT), "\n";

结果已经类似于Services_JSON的结果:

And the result is already similiar to the result with Services_JSON:

{
    "status": "OK",
    "users": {
        "user": [
            {
                "userName": "johndoe"
            },
            {
                "userName": "johndoe1",
                "fullName": "John Doe"
            },
            {
                "userName": "johndoe2"
            },
            {
                "userName": "johndoe3",
                "fullName": "John Doe Mother"
            },
            {
                "userName": "johndoe4"
            }
        ]
    }
}

但这不合适.如输出所示,缺少 searchResult 属性,并且用户不在所需的单个数组中.

But this is not fitting. As the output shows, the searchResult property is missing and also the users are not in a single array like you want them.

因此,json_encode需要由用户定义.为此,PHP具有JsonSerializable接口.它由一个名为jsonSerialize()的方法组成,如果名称为 searchResult ,我们现在将使其返回一个不同的值,以将其名称作为属性提供,并将用户作为平面数组提供.让我们扩展并实现该接口:

So the json_encode needs to be user-defined. To do this in PHP, PHP has the JsonSerializable interface. It consists of a single method named jsonSerialize() and we will make it return a different value now if the name is searchResult to offer both it's name as property and the users as a flat array. Let's extend and implement the interface:

class XML2JsonSearchResult extends XML2Json implements JsonSerializable
{

    public function jsonSerialize()
    {
        $name = $this->getName();

        if ($name !== 'searchResult') {
            return $this;
        }

        $value          = (array)$this;
        $value['users'] = iterator_to_array($value['users']->user, FALSE);

        return [$name => $value];
    }
}

所有不具有名称​​ searchResult 的元素都将通过返回$this来获取其默认JSON编码.

All elements that don't have the name searchResult will get their default JSON encoding by returning $this.

searchResult 将被命名,其用户将被iterator_to_array()函数压平.

The searchResult will be named and it's users are flattened by the iterator_to_array() function.

这就是您需要做的.同样,用法示例,它的工作原理完全相同,只是这次的类名不同:

And that is all you need to do. Again the usage-example, it works exactly the same, only this time the class-name differs:

$converter = new XML2JsonSearchResult($bufferXml);

echo json_encode($converter, JSON_PRETTY_PRINT);

现在输出就像您想要的一样:

And the output now is like you want it:

{
    "searchResult": {
        "status": "OK",
        "users": [
            {
                "userName": "johndoe"
            },
            {
                "userName": "johndoe1",
                "fullName": "John Doe"
            },
            {
                "userName": "johndoe2"
            },
            {
                "userName": "johndoe3",
                "fullName": "John Doe Mother"
            },
            {
                "userName": "johndoe4"
            }
        ]
    }
}

希望这为您提供了一个很好的示例,如今该怎么做.

Hope this gives you a good example how to do it nowadays.

一目了然的整个代码示例(在线演示):

The whole code-example at a glance (Online Demo):

class XML2JsonSearchResult extends SimpleXMLElement implements JsonSerializable
{

    public function jsonSerialize()
    {
        $name = $this->getName();

        if ($name !== 'searchResult') {
            return $this;
        }

        $value          = (array)$this;
        $value['users'] = iterator_to_array($value['users']->user, FALSE);

        return [$name => $value];
    }
}

$converter = new XML2JsonSearchResult($bufferXml);

echo json_encode($converter, JSON_PRETTY_PRINT);

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

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