【问题标题】:Handling JSON object from Twitter API response处理来自 Twitter API 响应的 JSON 对象
【发布时间】:2017-02-10 16:37:59
【问题描述】:

我想通过 Twitter API 检索关注某个其他用户(例如 @Google)的用户的所有 Twitter ID。虽然该请求在 Postman 中有效,但我无法使其在 PHP 中有效。看来 $userids 不是字符串,所以 json_decode 无法处理。代码如下。感谢您的帮助!

<?php
require "twitteroauth/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');

$consumerKey = 'redacted';
$consumerKeySecret = 'redacted';
$accessToken = 'redacted';
$accessTokenSecret = 'redacted';
$cursor = -1; // first page

$connection = new TwitterOAuth($consumerKey, $consumerKeySecret, $accessToken, $accessTokenSecret);
$content = $connection->get("account/verify_credentials");

$userids = $connection->get("followers/ids", ["cursor" => -1, "screen_name" => "google", "count" => 5000]);

echo $userids;

$data = json_decode($userids);
foreach ($data as $ids => $value) {
    // tbd
}
var_dump($data);

?>

【问题讨论】:

  • 那么代码的实际行为是什么? “看来$userids 不是字符串” - 你能检查一下吗?

标签: php json rest api twitter


【解决方案1】:

$userids 是一个数组,您可以在 TwitterOAuth 源代码中看到:

$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);

这意味着您不必再次对其进行 json_decode(),因为它已经是一个 PHP 数组。

【讨论】:

  • 好的,谢谢!我现在正在尝试检查保存在数组中的每个用户 ID 和光标(位于响应的最后)以将它们保存在数据库中。在引入数据库复杂性之前,我只想回显 ID 以查看它是否有效。但是,当我使用以下代码时:for ($i=0; $i&lt;=5000; $i++) { echo "&lt;pre&gt;"; echo $userids["ids"]; echo "&lt;/pre&gt;"; } 我收到以下错误:Fatal error: Cannot use object of type stdClass as array in /Applications/XAMPP/xamppfiles/htdocs/fetchusers.php on line 35 --- 可能是一个微不足道的错误,但我被卡住了。谢谢!
  • 编辑:已解决。 $userids 显然是 StdClass 的一个对象,它包含(!)数组“ids”。所以解决方案是 echo $userids-&gt;ids[5]; 获取例如 id 编号 5 和 echo $userids-&gt;next_cursor; 获取光标属性。
  • 如果你想知道变量是什么类型,你可以随时使用gettype($var)
猜你喜欢
  • 1970-01-01
  • 2017-10-12
  • 2012-06-28
  • 2016-02-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多