【问题标题】:GET a JSON Array with an API in PHP?使用 PHP 中的 API 获取 JSON 数组?
【发布时间】:2017-05-30 04:43:06
【问题描述】:

基本上,我正在尝试获取一个提供 JSON 数组的 API。它应该只有一个整数。每当我尝试尽管收到错误时:

Notice: Trying to get property of non-object in /public_html/call.php on line 16

这里是call.php:

    <?php
require 'connection.php';

$players2weeks = '(removed api)';


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response);

print_r($response);
echo $response->players_2weeks;
?>

我有用于故障排除的 print_r,但我什么也没得到。顺便说一下,对于一个菜鸟问题,我深表歉意,我对 JSON 没有经验。

感谢您的帮助!

【问题讨论】:

  • 首先打印你的 json 响应。
  • 请尝试$response = json_decode($response,true); print_r($response); echo $response['players_2weeks'];
  • 试试$response['players_2weeks'] 因为你解码了json对象。
  • 我认为它会返回一个数组而不是对象。首先粘贴您的JSON 回复。
  • 谢谢@ArshadShaikh。我不再收到该错误。如果我想在公式中使用查询结果,我该怎么做?有人告诉我我使用的是非数字值。

标签: php arrays json api


【解决方案1】:

我认为您可以使用此代码:

<?php
require 'connection.php';

$players2weeks = '(removed api)';


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
curl_close($ch);

$responses = json_decode($response);

print_r($responses);
echo $responses['players_2weeks'];
?>

你应该在解码的 JSON 对象时改变 echo 的格式。和变量相同意味着打印中的一些冲突,所以我也更改了$response 变量...

【讨论】:

  • 感谢您的回复,但是,仍然没有收到任何输入,并且在公式中不起作用。这是我的公式代码: require 'call.php'; $player2weeks_result = $responses; $a = 1; $b = 2; $公式 = ($player2weeks_result-($player2weeks_result*$a))-(($player2weeks_result-($player2weeks_result*$a))*$b);回声$公式;
  • 把你的$player2weeks_result = $responses改成这个$player2weeks_result = $responses['players_2weeks']
  • 打印echo $responses['players_2weeks'];this得到什么结果?
  • 请张贴您的 JSON 打印件
  • print_r($player2weeks_result) 没有显示任何内容
【解决方案2】:

您必须使用 api 上的 json_encode() 函数将数组转换为 json 字符串。

例如:xxx.php(api)

$result = 数组(); //返回数组
echo json_encode($result);

然后你可以通过api调用者的json数组得到结果。

var_dump(json_decode($result));           // Object
var_dump(json_decode($result, true));     // Associative array

【讨论】:

  • 不幸的是,这不是我的 API。 API 只是告诉我它以 JSON 数组的形式返回结果。
  • 如果您正在访问 HTTPS URL 并且您没有收到任何内容,请尝试禁用验证 SSL。
  • 我已经添加了这些选项,但它给了我一个 HTTP 500 错误。
  • 500 Internal Server Error 是服务器端错误,这意味着问题可能不是您的计算机或互联网连接,而是网站服务器的问题。
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
相关资源
最近更新 更多