我确信我错过了一些东西,但目前我不明白是什么。
我正在玩 Guzzle,我正在尝试获取页面信息:
<?php
/**
* Example of usage of APIConnect to get information
* about a Facebook Page through Graph API.
*/
require('../vendor/autoload.php');
/** SET HERE A PAGE */
$page = 'SamplePage';
$remoteUrl = 'https://graph.facebook.com/' . $page;
$client = new GuzzleHttp\Client();
$res = $client->get($remoteUrl);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
这是 Guzzle 文档显示的代码。
现在,我期望调用此代码会返回一些对象,这些对象在其属性之一中包含以下 JSON 响应,因为如果我直接在浏览器中调用 URL,我会收到该响应:
{
"error": {
"message": "An access token is required to request this resource.",
"type": "OAuthException",
"code": 104
}
}
为什么,如果我使用 Guzzle 方法获取响应值,我会看到它是 null
?我错过了什么?
最佳答案
好的,我解决了这个问题。
第一个问题是我使用了旧版本的 Guzzle。
在我的composer.json 中我有这个:
## THIS IS WRONG ##
"require": {
"guzzlehttp/guzzle": "*@stable"
},
但是这样我下载了Guzzle 3,那是一个旧版本。
To download the new version (the 6) ,我是这样改行的:
## THIS IS CORRECT ##
"require": {
"guzzlehttp/guzzle": "~6"
},
所以,我现在有了 Guzzle 6。
代码也必须更改。这是正确的版本:
<?php
/**
* Example of usage of APIConnect to get information
* about a Facebook Page through Graph API.
*/
require('../vendor/autoload.php');
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$url = 'https://graph.facebook.com/SamplePage'; // Set the URL
$api_end_point = '';
$end_point = '';
$client = new Client(
['base_uri' => $url]
);
$path = $api_end_point . $end_point;
echo $path;
try
{
$res = $client->get($path);
}
catch (RequestException $e)
{
$res = $e->getRequest();
if ($e->hasResponse())
{
$res = $e->getResponse();
}
}
echo $res->getStatusCode();
// "400"
print_r($res->getHeader('content-type'));
// Array ( [0] => text/javascript; charset=UTF-8 )
echo $res->getBody();
// {"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104}}
现在 Guzzle 返回响应。这是一个 400 状态代码,因为我们需要身份验证,但这是另一个问题:)
关于php - 如何使用 Guzzle 获取 Facebook 页面信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410894/