How to print Twitter API request reply? - php

I want to print all the tweets from the reply. What am I missing?
https://github.com/J7mbo/twitter-api-php
<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
/** Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=%23twitter';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
foreach ($response->statuses as $tweet) {
echo $tweet->text;
}
Notice: Trying to get property of non-object in
/var/www/projects/twitter/twitter-api-php/index.php on line 23
Warning: Invalid argument supplied for foreach() in
/var/www/projects/twitter/twitter-api-php/index.php on line 23

The performRequest() method returns a JSON string, not an array, so you need to decode it $array = json_decode($response, true);.

You just have to use:
`echo $response;`
or instead:
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
but I recommend using the first approach.

Related

Problems with looping a json

Here I have a json which i get after making a request to the twitter API. I have already seen different working examples of looping a json. Even I have do it in another projects. But this time it isn't working.
I've tested a lot of things. I guess it's normal it doesn't work for now. The variable arrayFriends isn't even being used. Just i was testing some moves.
Don't know exactly where I am failing. I would like to have some feedback
Thank you guys!
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = '?screen_name=J7mb0';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));
$arrayFriends = var_dump(json_decode($json, true, 512, JSON_BIGINT_AS_STRING));
$json = json_decode($json, true);
echo $json;
foreach($json->ids as $obj){
echo $obj->ids;
}
If you're using json_decode with true, the returned value will be an array, not an object.
Therefore, you won't be able to use the property-access method here:
foreach($json->ids as $obj){
You have to use the array-access method instead:
foreach($json['ids'] as $obj){
or, change the parameter at decoding, so you get an object:
$json = json_decode($json, false);
// or just simply:
// $json = json_decode($json);
// since the second parameter defaults to FALSE
ALSO, $arrayFriends will remain empty, because var_dump returns nothing at all.
// Change this:
// $arrayFriends = var_dump(json_decode($json, true, 512, JSON_BIGINT_AS_STRING));
// ...to this:
$arrayFriends = json_decode($json, true);
It worked! After trying different things it started working.
Actually I'm trying to access another json but this isn't working. It is the same app but with more content.
$user = 'seyroku';
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = '?screen_name='.$user.'';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));
$arrayFriends = json_decode($json, true,512,JSON_BIGINT_AS_STRING);
foreach($arrayFriends['ids'] as $obj){
echo $obj,",";
$url2 = 'https://api.twitter.com/1.1/users/lookup.json';
$getfield2 = '?user_id='.$obj.'';
$json2 = $twitter->setGetfield($getfield2)
->buildOauth($url2, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));
echo $twitter->setGetfield($getfield2)
->buildOauth($url2, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));
$json3 = json_decode($json2, true);
foreach ($json3['name'] as $nombre) {
echo $nombre,",";
}
/* $sql = "INSERT INTO friendtest (user, friends)
VALUES ('$user' , '$obj' )";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}*/
}
The first for each it returns me the id properly. But the second one which I expect to give me the name of that id doesn't do it. I tried different things but still isn't working.
Could you give me some feedback?
Sorry guys for being so bad at this.

Require once/include not finding correct file laravel

Require once/include in my laravel project is not functioning properly. I am using the correct path however i continue to get the same error. I can see the file is in the designated space. What could cause this? Here is my code:
#extends('apps.admin')
#section('main')
<?php
include(app_path().'vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "token",
'oauth_access_token_secret' => "token",
'consumer_key' => "token",
'consumer_secret' => "token"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#nerd';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
var_dump(json_decode($response));
?>
#stop
I also tried this:
require_once('vendor/j7mbo/TwitterAPIExchange.php');
and this:
require_once('TwitterAPIExchange.php');
errors:
include(/var/www/web/elephantegin/htdocs/app/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php): failed to open stream: No such file or directory (View: /var/www/web/elephantegin/htdocs/resources/views/socialApps/twitter.blade.php)
errror:
main(): Failed opening required '/vendor/j7mbo/TwitterAPIExchange.php' (include_path='.:/usr/share/php:/var/www/web/elephantegin/htdocs')
You are referencing the file incorrectly, use the correct path:
include(app_path().'../vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php');

Parsing JSON response from James Mallison twitter library

I am using the Twitter Search API 1.1 to search followers_count
I have managed to get the Oauth working with the help of James Mallison at http://github.com/j7mbo/twitter-api-php.
Here my code :
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "yyy",
'consumer_key' => "zzz",
'consumer_secret' => "vvv"
);
$url = 'https://api.twitter.com/1.1/users/lookup.json';
$getfield = '?screen_name=twitterapi';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($twitter, true);
$ed = $response->followers_count;
Here the answer :
[{"id":6253282,"id_str":"6253282","name":"Twitter API","screen_name":"twitterapi","location":"San Francisco, CA","description":"The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.","url":"http:\/\/t.co\/78pYTvWfJd","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/78pYTvWfJd","expanded_url":"http:\/\/dev.twitter.com","display_url":"dev.twitter.com","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":3402865,"friends_count":48,"listed_count":12958,"created_at":"Wed May 23 06:01:13 +0000 2007","favourites_count":27,"utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"verified":true,"statuses_count":3535,"lang":"en","status":{"created_at":"Thu May 21 21:12:42 +0000 2015","id":601495856353783808,"id_str":"601495856353783808","text":"RT #TwitterDev: We are excited to announce that the REST API now supports native video upload. https:\/\/t.co\/cWUrgjh8wz http:\/\/t.co\/yaenTQE9\u2026","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Thu May 21 20:57:40 +0000 2015","id":601492072953151488,"id_str":"601492072953151488","text":"We are excited to announce that the REST API now supports native video upload. https:\/\/t.co\/cWUrgjh8wz http:\/\/t.co\/yaenTQE95N","source":"\u003ca href=\"http:\/\/jonbulava.com\" rel=\"nofollow\"\u003eJon's Developer Testing App\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":160,"favorite_count":189,"entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[{"url":"https:\/\/t.co\/cWUrgjh8wz","expanded_url":"https:\/\/blog.twitter.com\/2015\/rest-api-now-supports-native-video-upload","display_url":"blog.twitter.com\/2015\/rest-api-\u2026","indices":[79,102]}],"media":[{"id":601491637433475073,"id_str":"601491637433475073","indices":[103,125],"media_url":"http:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","media_url_https":"https:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","url":"http:\/\/t.co\/yaenTQE95N","display_url":"pic.twitter.com\/yaenTQE95N","expanded_url":"http:\/\/twitter.com\/TwitterDev\/status\/601492072953151488\/video\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":340,"h":191,"resize":"fit"},"large":{"w":640,"h":360,"resize":"fit"},"medium":{"w":600,"h":337,"resize":"fit"}}}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"en"},"retweet_count":160,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"user_mentions":[{"screen_name":"TwitterDev","name":"TwitterDev","id":2244994945,"id_str":"2244994945","indices":[3,14]}],"urls":[{"url":"https:\/\/t.co\/cWUrgjh8wz","expanded_url":"https:\/\/blog.twitter.com\/2015\/rest-api-now-supports-native-video-upload","display_url":"blog.twitter.com\/2015\/rest-api-\u2026","indices":[95,118]}],"media":[{"id":601491637433475073,"id_str":"601491637433475073","indices":[119,140],"media_url":"http:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","media_url_https":"https:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","url":"http:\/\/t.co\/yaenTQE95N","display_url":"pic.twitter.com\/yaenTQE95N","expanded_url":"http:\/\/twitter.com\/TwitterDev\/status\/601492072953151488\/video\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":340,"h":191,"resize":"fit"},"large":{"w":640,"h":360,"resize":"fit"},"medium":{"w":600,"h":337,"resize":"fit"}},"source_status_id":601492072953151488,"source_status_id_str":"601492072953151488","source_user_id":2244994945,"source_user_id_str":"2244994945"}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"en"},"contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/6253282\/1431474710","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false}]
Warning: json_decode() expects parameter 1 to be string, object given in ...
I don't kwnow why i can't use json_decode
Any feedback or ideas on how to reach followers_count correctly would be much appreciated.
Cheers
What you need to do is:
$jsonResponse = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$data = json_decode($jsonResponse, true);
$ed = $data[0]['followers_count'];
Here json_decode documentation.

PHP (Xampp vs Mamp)

I am new as a programer in PHP, I have Macbook Pro so I have installed mamp for it and it all worked well while now I am using xampp and same program not working in xampp.
Program is as follows:
<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "47w756hhd7jBU0yXqOfeJQKlgXYD",
'oauth_access_token_secret' => "YjhdfhUE1hYaNu5E4IiU0gZnqt1kp5nSUy1lP",
'consumer_key' => "878bdfdffhEOXx5AdJhpelO9ZNStb",
'consumer_secret' => "jhfhrhXjJ867vvIRSwsI6CJuhUIEYoj0iGHGNpIPkXJ3lcTP9W"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getfield = '?q=#varanasi&result_type=recent';
//this code converts json code into simple string object
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
echo $string;
if($string["errors"][0]["message"] != "") {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";
exit();
}
echo "<pre>";
print_r($string);
echo "</pre>";
if(empty($string))
{
echo "hello there is nothing";
}
else
{
echo "hello everything:";
}
?>
Now the $string is showing empty data in xampp while in mamp it is all working well.
I've solved this by editing TwitterAPIExchange.php file.
Just adding
CURLOPT_SSL_VERIFYPEER => false
at the $options array at the performRequest method

how to apply CSS / HTML in twitter API JSON results

using below code, TWITTER API and PHP, i have successfully fetch/get my twitter timeline.
$url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$getfield = '?screen_name=twitter';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
my concern is, the data/results displayed fills up my whole window screen with text. im not sure how to apply CSS or HTML on it.
[{"created_at":"Sun Dec 09 05:21:29 +0000 2012","id":2232376342522313442,"id_str":"277231523253442","text":"http:\/\/t.co\/ro74jh4","source":"web","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"
the tutorial im following didn't mentioned how to arrange the fetched data.
You'll need to parse the JSON data that you got from object from Twitter. Here is an example. You can use the array syntax to find which values you want to look up.
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$obj = json_decode($response, true);
echo "<div><ul>";
foreach ($obj["statuses"] as $index => $result) {
$tweet = $result['text'];
$user = $result['user']['screen_name'];
$profile_image = $result['user']['profile_image_url'];
echo "<li>";
echo "<img src=\"".$profile_image."\" width=\"25px\" height=\"25px\" />";
echo "#$user";
echo " $tweet";
echo "</li>";
}
echo "</ul></div>";

Categories