curl 如何使用PHP7.4从API解码JSON数据

nxagd54h  于 2022-11-13  发布在  PHP
关注(0)|答案(2)|浏览(180)

我使用cURL连接到api并接收JSON响应。无法使用PHP解析数据,原因是 PHP错误:'正在尝试访问int类型的值上的数组偏移量' 我使用了json_decode(),但仍然收到错误。我还尝试通过将第二个参数设置为'true'和'false'来解码为数组和对象。我使用了gettype(),并收到了NULL响应。我使用的是PHP 7.4.3,但我相信这在旧版本的PHP中也能工作。那么在这些新版本中我们如何将JSON解析为PHP对象或数组呢?
下面是从api返回的JSON:
{"count":8,"next":"https://pokeapi.co/api/v2/generation/?offset=2&limit=2","previous":null,"results":[{"name":"generation-i","url":"https://pokeapi.co/api/v2/generation/1/"},{"name":"generation-ii","url":"https://pokeapi.co/api/v2/generation/2/"}]}
下面是我PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://pokeapi.co/api/v2/generation/?limit=2');

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$output = curl_exec($ch);

curl_close($ch);

$decoded = json_decode($output, false);

echo $decoded->count;

//  i've also tried:
//  $decoded = json_decode($output, true);
//  echo $decoded['count']

//  as well as $decoded = json_decode($output);```
xriantvc

xriantvc1#

您必须指定curl CURLOPT_RETURNTRANSFER,以便它可以将值作为字符串返回

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://pokeapi.co/api/v2/generation/?limit=2',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$output = curl_exec($curl);

curl_close($curl);

$decoded = json_decode($output);

echo $decoded->count;

?>

这里有更多的选项可以帮助你https://www.php.net/manual/en/function.curl-setopt.php

k4ymrczo

k4ymrczo2#

请注意,json_decode解码JSON string
因此,使用json_decode来解码json字符串,它应该可以工作:

<?php
$output='{"count":8,"next":"https://pokeapi.co/api/v2/generation/?offset=2&limit=2","previous":null,"results":[{"name":"generation-i","url":"https://pokeapi.co/api/v2/generation/1/"},{"name":"generation-ii","url":"https://pokeapi.co/api/v2/generation/2/"}]}';

$decoded = json_decode($output, false);

echo "Count is " . $decoded->count;
echo "<br>";

echo "1st name is " . $decoded->results[0]->name;
echo "<br>";

echo "2nd name is " . $decoded->results[1]->name;
echo "<br>";

?>

检查此沙箱(已尝试:- PHP 7.4.32工作)
https://onlinephp.io/c/a48d3

其他信息

对于您的情况,您可以简单地使用file_get_contents来替换curl:

<?php
$url="https://pokeapi.co/api/v2/generation/?limit=2";

$output = file_get_contents($url, true);

?>
<?php

$decoded = json_decode($output, false);

echo "Count is " . $decoded->count;
echo "<br>";

echo "1st name is " . $decoded->results[0]->name;
echo "<br>";

echo "2nd name is " . $decoded->results[1]->name;
echo "<br>";

?>

相关问题