我的Api(laravel)使用Json代码。现在我也想支持xml。 Xml消息必须转换为Json,以便适合现有结构。但是我无法将XML与所需的Json格式匹配。
示例XML并转换为Json:
$xml = "<?xml version='1.0'?>
<catalog>
<book>
<author>Jan</author>
<title>Xml to Json Array</title>
<pages>
<page>
<nr>1</nr>
<title>Welcome to my book</title>
<pagereviews>
<pagereview>
<name>maikel</name>
<comment>very good</comment>
</pagereview>
<pagereview>
<name>John</name>
<comment>i like this page</comment>
</pagereview>
</pagereviews>
</page>
<page>
<nr>2</nr>
<title>more info</title>
</page>
<page>
<nr>3</nr>
<title>lots of fun</title>
</page>
</pages>
</book>
</catalog>";
$xmlObject = simplexml_load_string($xml);
$jsonString = json_encode($xmlObject);
return $jsonString;
在Json中,结果为:
{
"book": {
"author": "Jan",
"title": "Xml to Json Array",
"pages": {
"page": [
{
"nr": "1",
"title": "Welcome to my book",
"pagereviews": {
"pagereview": [
{
"name": "maikel",
"comment": "very good"
},
{
"name": "John",
"comment": "i like this page"
}
]
}
},
{
"nr": "2",
"title": "more info"
},
{
"nr": "3",
"title": "lots of fun"
}
]
}
}
}
我需要没有标签Page和Pagereview的标签。这样。
{
"book": {
"author": "Jan",
"title": "Xml to Json Array",
"pages": [
{
"nr": "1",
"title": "Welcome to my book",
"pagereviews": [
{
"name": "maikel",
"comment": "very good"
},
{
"name": "John",
"comment": "i like this page"
}
]
},
{
"nr": "2",
"title": "more info"
},
{
"nr": "3",
"title": "lots of fun"
}
]
}
}
答案 0 :(得分:-1)
我制作了几个与Laravel集成以简化XML的软件包。您可以在此处查看它们:
如果您的xml需要与json的结构不同,我建议您做一下Spatie's Fractal package。它将介绍用于您的数据的转换器。然后,您可以在使用我的程序包之前有条件地设置转换器,以使数据完全按您的要求输出。