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.
Related
I know it's basic, but I couldn't get what's wrong because it's not my area.
I am sending some request to a server and print the response like this:
$rest = curl_init();
curl_setopt($rest,CURLOPT_URL,$url);
curl_setopt($rest,CURLOPT_GET,1);
curl_setopt($rest,CURLOPT_HTTPHEADER,$headers);
curl_setopt($rest,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($rest,CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($rest);
$json = json_decode($response, true);
echo $response;
Where I get this:
{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}
Then, I am trying to print the JSON or its fields, but I then get nothing:
echo $json;
echo $json['UserID'];
echo $json['Devices'];
To clarify the comments a bit:
$str = '{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}';
$json = json_decode($str, true); // to an associative array
// to echo the UserID
echo "userID : " . $json['results'][0]['UserID'];
// output: userID : 433011AC-228A-4931-8700-4D050FA18FC1
// to get the structure of the json array in general use print_r() as AbraCadaver pointed out
print_r($json);
In your attempt you were missing the results[0] part.
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.
So I'm having a problem with the following code.
I've got CURLOPT_RETURNTRANSFER set to true, yet nothing is returned when curl_exec is hit. Any and all help is appreciated!
<?php
$yql_base_url = "http://query.yahooapis.com/v1/public/yql?q=";
$yql_query = "select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=YHOO,GOOG,AAPL&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'";
$yql_params = "&format=json&diagnostics=true&callback=";
$yql_url = $yql_base_url . urlencode($yql_query) . $yql_params;
$session = curl_init($yql_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
curl_close($session);
$phpObj = json_decode($json);
if(!is_null($phpObj->query->results))
{
echo $phpObj->query->results;
}
?>
$phpObj->query->results is an array of Object and you can not do echo on it. Simply use print_r() or var_dump() on it.
Example:
print_r($phpObj->query->results);
var_dump($phpObj->query->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>";
Hello :) I apologize in advance if this is really dumb, but I've been trying to figure it out for a week and now I'm about to explode :D
I have a list of 200 ID numbers in a text file, each are separated by a newline. I want to use PHP to use each line, one by one, as a variable in a POST request. I can use this code to send the first line, by specifying the number of characters to include from the file:
$IDfile = "file.txt";
$fh = fopen($IDfile, 'r');
$ID = fread($fh, 18);
fclose($fh);
Then I can use the $ID variable in the POST. But this is only good for the first line, since there are 18 characters in the line, but there are 199 more lines.
I can also print all the lines in the file with a foreach, but this won't help with the POST requests:
$IDfile = "file.txt";
$lines = file($IDfile);
foreach($lines as $line_num => $line)
{
echo $line;
echo "<br>";
}
So, here is the full script of my POST request, to send a "destroy tweet" command to the Twitter API 1.1 - The $ID variable is the one I want to replace using every line in the text file sequentially:
require_once('TwitterAPIExchange.php');
include('apikeys.php');
$url = "https://api.twitter.com/1.1/statuses/destroy/" .$ID . ".json";
$requestMethod = 'POST';
$postfields = array(
);
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
So how do I do it? How can I get each line sequentially from the text file, and then use the single line value as a variable in the POST request, until each has been read?
This is probably way out of my league lol, but I am determined to learn this, and any help or direction would be so very gratefully received :)
Try this, if i am right your must contain the id field
<?php
require_once( "TwitterAPIExchange.php" );
include( "apikeys.php" );
$url = "https://api.twitter.com/1.1/statuses/destroy/%s.json";
$lines = file( "file.txt" );
$post = array(
"id" => null
);
foreach( $lines as $line ) {
$line = trim( $line );
$post["id"] = $line;
$twitter = new TwitterAPIExchange( $settings );
$response = $twitter->buildOauth( sprintf( $url, $line ), "POST" )
->setPostfields( $post )
->performRequest();
$response = json_decode( $response );
if ( !$response ) {
echo "Empty response";
break;
}
var_dump( $response );
}
?>
Use fopen to read the file and then inside the loop you can create the URL and send a POST request, like so:
$f = fopen("file.txt", "r");
while(!feof($f)) {
$url = "https://api.twitter.com/1.1/statuses/destroy/" . trim($f) . ".json";
$requestMethod = 'POST';
$postfields = array(
);
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
}
Something along these lines should help you solve that issue
$IDfile = "file.txt";
$lines = file($IDfile);
foreach($lines as $line_num => $line)
{
echo sending request for $line;
$url = "https://api.twitter.com/1.1/statuses/destroy/" .$line . ".json";
$requestMethod = 'POST';
$postfields = array(
);
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
}