如何在php中访问json数组并将其保存在.json文件中
当前PHP代码正常工作,但我需要保存JSON,正如我在示例中提到的那样 我需要访问数组的所有数据并将其保存在.JSON文件中如何在php中访问json数组并将其保存在.json文件中,php,arrays,json,Php,Arrays,Json,当前PHP代码正常工作,但我需要保存JSON,正如我在示例中提到的那样 我需要访问数组的所有数据并将其保存在.JSON文件中 <?php $curl = curl_init(); $fh = fopen('local.json','w'); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_URL, "https://jsonstorage.net/ap
<?php
$curl = curl_init();
$fh = fopen('local.json','w');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, "https://jsonstorage.net/api/items/46b5a62d-9a39-41ab-89f4-e75f458c9189");
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
fwrite($fh, $contents);
curl_close($curl);
fclose($fh);
?>
我想要的回答是:
{
"data": [
**I want this data**
]
}
以下是我的需求示例:
[
{
"adapterid": 44835,
"rowid": 1573784208932,
"battery": 3610,
"createddate": "15-11-2019",
"gid": "01:f0:50:11:a1:35:87",
"id": 2277491836402479600,
"projectid": 32107,
"rssi": -90,
"temp": 25.75
},
{
"adapterid": 44835,
"rowid": 1573784212032,
"battery": 3660,
"createddate": "15-11-2019",
"gid": "01:f0:50:11:a1:35:87",
"id": 2277491836402479600,
"projectid": 32107,
"rssi": -89,
"temp": 25.75
},
{
"adapterid": 44835,
"rowid": 1573784215034,
"battery": 3610,
"createddate": "15-11-2019",
"gid": "01:f0:50:11:a1:35:87",
"id": 2277491836402479600,
"projectid": 32107,
"rssi": -96,
"temp": 25.75
}
]
我怎样才能访问这个?
提前感谢试试这个:
$contents = json_decode($contents,1);
print_r($contents['data']);
您可以使用
json\u decode($contents,true)将json转换为关联数组代码>
这允许您检索json中的数据
数组,然后使用json_encode($contents['data'])将其转换回json代码>将数据写入文件:
<?php
$curl = curl_init();
$fh = fopen('local.json', 'w');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, "https://jsonstorage.net/api/items/46b5a62d-9a39-41ab-89f4-e75f458c9189");
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
$contents = json_decode($contents, true); // to associative array
$contents = json_encode($contents['data']); // to json, only the 'data' array
fwrite($fh, $contents); // write json 'data' array to file
curl_close($curl);
fclose($fh);
<?php
$curl = curl_init();
$fh = fopen('local.json', 'w');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, "https://jsonstorage.net/api/items/46b5a62d-9a39-41ab-89f4-e75f458c9189");
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
$contents = json_decode($contents, true); // to associative array
$contents = json_encode($contents['data']); // to json, only the 'data' array
fwrite($fh, $contents); // write json 'data' array to file
curl_close($curl);
fclose($fh);