【问题标题】:Get data from URL in php contains error从 php 中的 URL 获取数据包含错误
【发布时间】:2016-01-20 00:03:20
【问题描述】:

我正在尝试从URL 获取数据。它包含 Facebook 用户的好友列表。我必须pass fbid and access-token。它会return friend list
这里是网址:

<?php
$url = "https://graph.facebook.com/$fbid/friends?access_token=$fb_accesstoken";
?>

但是这个URL 包含错误:

{
   "error": {
      "message": "Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.",
      "type": "OAuthException",
      "code": 190,
      "error_subcode": 460,
      "fbtrace_id": "BSpC5i0A6Oo"
   }
}

所以我把条件写成这样:

<?php
if(!strpos($url, 'error')) {
   $data = file_get_contents($url);
   // further process.
} else {
   $data = array();
}
?>

我可以理解给出的错误,但我也为此设置了条件,但它仍然给了我相同的条件。 我该如何解决这个问题?

【问题讨论】:

  • 不是“包含错误”的 URL,而是您在请求该 URL 时得到的 响应。检查 URL 是否包含文本 error 因此没有任何意义。

标签: php facebook url file-get-contents


【解决方案1】:

你应该使用 json_decode 函数。

$url = "https://graph.facebook.com/$fbid/friends?access_token=$fb_accesstoken";

$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

$response = json_decode(curl_exec($curlSession));
curl_close($curlSession);

if(!isset($response['error'])) {
     // further process.
     // Do whatever 
} else {
     $data = array();
}

【讨论】:

  • $data 只是字符串。所以我用strpos
  • 流程应该是:构建 URL > 调用 > 获取数据 > 解析 > 根据响应执行任何操作。
  • 但是从这个 url 停止了
  • 调用 URL 时需要检查响应中的错误。在您的代码中检查$url 变量中的错误。
  • 但是当我调用 url 时,它会停止并给我错误
【解决方案2】:

你可以通过 CURL 读取数据

 <?php
        $curlSession = curl_init();
        curl_setopt($curlSession, CURLOPT_URL, 'https://graph.facebook.com/$fbid/friends?access_token=$fb_accesstoken');
        curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

        $jsonData = json_decode(curl_exec($curlSession));
        curl_close($curlSession);
    ?>

如果您只想要原始 JSON 数据,则只需删除 json_decode

【讨论】:

  • 从 url 我得到字符串数据。
  • 那是什么问题
  • strpos 未检查
  • if(strpos($url, 'error') !== false) { // 在这里做点什么 } 检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 2021-05-19
  • 2016-08-06
  • 2013-05-06
  • 1970-01-01
  • 2012-09-11
相关资源
最近更新 更多