php xml数据以json格式编码

时间:2018-07-04 12:05:00

标签: php json xml

这是我的php文件代码,我在其中从thecatapi中获取数据 我需要数据表的特定格式

$xml=file_get_contents('https://thecatapi.com/api/images/get?format=xml&results_per_page=3');
 $xml = new SimpleXMLElement($xml);

 $datas=array();

$datas['rows'] = $xml->data->images;

echo json_encode($datas, true);

输出为:

{"total":50,
 "rows":{"image":[
            {"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
            "id":"e0i",
            "source_url":"http:\/\/thecatapi.com\/?id=e0i"
            },
            {"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
            "id":"MTYwNDE0MQ",
            "source_url":"http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
            },{
            "url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
            "id":"bon",
            "source_url":"http:\/\/thecatapi.com\/?id=bon"
            }
            ]
        }
}

但是我想要这种json形式

{
  "total": 800,
  "rows": [
    {
      "url": 0,
      "id": "Item 0",
      "source_url": "$0"
    },
    {
      "url": 0,
      "id": "Item 0",
      "source_url": "$0"
    },
    {
      "url": 0,
      "id": "Item 0",
      "source_url": "$0"
    },

1 个答案:

答案 0 :(得分:-1)

只是想出了一个替代解决方案。更改此行:

$datas['rows'] = $xml->data->images;

对此:

$datas['rows'] = $xml->data->images->image;

否则您仍然可以这样做

将json字符串解码为一个对象,然后根据需要对其进行修改。

$stdClassObject = json_decode($jsonData);

$stdClassObject->rows = $stdClassObject->rows->image;

$newJsonData = json_encode($stdClassObject, JSON_PRETTY_PRINT);

echo '<pre>';
print_r($newJsonData);
echo '</pre>';

新输出:

{
    "total": 50,
    "rows": [
        {
            "url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
            "id": "e0i",
            "source_url": "http:\/\/thecatapi.com\/?id=e0i"
        },
        {
            "url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
            "id": "MTYwNDE0MQ",
            "source_url": "http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
        },
        {
            "url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
            "id": "bon",
            "source_url": "http:\/\/thecatapi.com\/?id=bon"
        }
    ]
}
相关问题