I’m attempting to use twitteroauth to retrieve tweets using the Twitter search API.
Here is my code:
/* Load required lib files. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
/* If method is set change API call made. Test is called by default. */
$content = $connection->get('account/verify_credentials');
$url = $_GET["url"];
$contents = $connection->get($url);
header ("Content-Type:text/json");
echo $contents;
I’m calling this PHP script from my JavaScript using XMLHttpRequest. I’ve verified that I’m using the correct URL (e.g. https://api.twitter.com/1.1/search/tweets.json?q=kate). The error I’m getting as a result is:
Catchable fatal error: Object of class stdClass could not be converted to string in OAuth/Twitter/loadJSON.php on line 26.
Line 26 is:
echo $contents;
I’ve looked at the get() function in the source code, and it looks like I should be expecting back a JSON string, but from the error message it would appear that’s not the case, or perhaps it’s not able to json_decode the response?
This is my first time using twitteroauth; any help would be greatly appreciated! Thanks.
Quite the opposite.
For some inane reason lost to time, the designer of
json_decodedecided it should return a set of nested stdClasses. You can’t directlyechoany class without it having a__toStringmagic method.If you’re trying to inspect the data, you’ll want to break out a better tool, like
var_dump, which can inspect any PHP data type.You might find stdClasses a bit irritating and disjointed to deal with. Pass
trueas the second parameter tojson_decode, and it will return a set of nested arrays instead.In this specific case, it looks like you want the JSON string passed along. While that doesn’t seem immediately possible through the library you’re using, sending the data on a trip through
json_encodeshould do the trick.