首页 > 解决方案 > Json 使用 PHP (curl) 从 API 将数据保存到 JSON 文件

问题描述

我编写了这段代码来从 API URL 获取数据。所有数据都写入我的文件,但我找不到解决方案让它看起来像文件中的 Json 格式,我错过了什么?我在文件中尝试的所有内容都显示为文本(下面添加了示例)和我想要的内容。也许有人会帮助我:)。谢谢!

使用php curl获取和保存数据的源代码

<?php
$token = "eyJ";
$ch = curl_init("https://api.xxx.com/api/Catelo/Prod?cat=MPHEFGZ");
$fp = fopen("prod.json", "w");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token
   ));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

我希望它像这样保存到文件中:

我的期望(保存格式):

"FIFA_Last_World_Cup_final":
{
    "Year": "2018",
    "data":
    {
        "Winner": "France",
        "Score": "4-2",
        "Runner-up": "Croatia"
    }
}

将数据保存到文件时我现在得到的结果:

[{"id":1,"Code":1,"name":"TV","manu":"32","v":"P","v":"P","c":"T","q":"0","p":1.0,"d":1.0,"imagePath":"e0bc7.Jpeg","thumbnailImagePath":"0bc7.Jpeg","fullDsc":"32\"","cury":"E","httpD":"548","packy":1,"ty":"24","eae":"","obligaKit":0,"reerty":0,"proate":0,"pront":70,"quane2":"0","pri":0.0,"lotN":"","p":0.0,"i":70}

标签: phpjsoncurl

解决方案


由于您没有处理来自 API 的响应,因此您所看到的只是响应的发送方式。要对其进行格式化,您可以捕获输出(使用CURLOPT_RETURNTRANSFER),然后解码响应 - 使用 重新编码JSON_PRETTY_PRINT

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $token
));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the JSON from the API
$response = curl_exec($ch);
curl_close($ch);
fclose($fp);

// Decode it, re-encode with formatting
echo json_encode(json_decode($response), JSON_PRETTY_PRINT);

推荐阅读