【问题标题】:Php xml data to json encode in specific formatphp xml 数据到 json 以特定格式编码
【发布时间】:2023-03-30 23:48:02
【问题描述】:

这是我从 catapi 获取数据的 php 文件代码 我需要数据表的特定格式

$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"
    },

【问题讨论】:

  • 什么意思?你只想美化json吗?如果是这样,只需使用 JSON_PRETTY_PRINT 选项
  • 由于您所需的输出与您开始的输出没有相似之处,我们将努力在这里提供很多帮助
  • 请记住,我们不是千里眼。我们只能对您向我们展示的内容发表评论,如果这没有意义,您也不会得到任何答案
  • @NobbyNobbs 不,先生,我不想只是美化它我已经尝试了一整天以这种格式格式化数据,因为引导数据表不接受其他格式,我不是专家引导数据表
  • 在您的 I want 示例中,您似乎已经删除了几乎所有内容。这就是为什么我不明白你想从这个过程中得到什么的例子

标签: php json xml


【解决方案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"
        }
    ]
}

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多