PHP and Twitter API

I’m struggling badly making a (apparently simple) php script for calling the twitter api and listing recent tweets. If anyone has any thoughts on this, I’m most appreciative. I THINK the crisis is in my require_once fucntion. Below the code is the link to it live, you can see what happens.

[php]<?php
session_start();
require_once(“twitteroauth.php”); //Path to twitteroauth library

$twitteruser = “username_here”;
$notweets = 10;
$consumerkey = “xxxxxxxxxxxxxxxx”;
$consumersecret = “xxxxxxxxxxxxxxxxxxxxx”;
$accesstoken = “xxxxxxxxxxxxxxxxxxxxxxj”;
$accesstokensecret = “xxxxxxxxxxxxxxxxx”;

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=”.$notweets);

echo json_encode($tweets);
?>[/php]

http://www.anxietyclown.com/TwitterO/get_tweets2.php

I’m noticing that ANYTIME I require_once or include an external file, it ends up displaying that file rather than executing it.

Post the twitteroauth.php file you are using as well. Sounds like you don’t start these files with <?php

Code is too long to post but yes it appears to be missing php tags. I’ll investigate more. THANKS!

Okay, inching forward. I am not able to receive a specified # of tweets but they return to me as a wall of text and information. I think the cause of this is the following code snippet:

[php]echo json_encode($tweets);[/php]

From what I understand, I need to var_dump or decode the information from the json? If I figure out how to do that, how do I know what information is returned and where in the array its placed?

Hard to say without seeing any code / response data. I haven’t worked with the twitter api before, but it doesn’t make sense to json_encode the result, are you sure you are not supposed to decode it?

Try this:
[php] <?php
session_start();
require_once(“twitteroauth.php”); //Path to twitteroauth library

$twitteruser = “username_here”;
$notweets = 10;
$consumerkey = “xxxxxxxxxxxxxxxx”;
$consumersecret = “xxxxxxxxxxxxxxxxxxxxx”;
$accesstoken = “xxxxxxxxxxxxxxxxxxxxxxj”;
$accesstokensecret = “xxxxxxxxxxxxxxxxx”;

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=”.$notweets);

$tweetData = json_decode($tweets);
echo ‘

’;
var_dump($tweetData);[/php]

I think what you’re suggesting will work (All I get echoed is NULL right now) but I’m not sure how to unravel that var_dump. I don’t know how many fields are in the array or what is in each field. Is there a way to loop through an array, without knowing its depth/length, and echo the contents on screen?

Var dumping the object should display all data within. Try var dumping $tweets and see if what you’ve got there is valid json.

JSON validator:
http://jsonlint.org/

if you’re still having problems please paste the data of $tweets here and someone will be able to have a look at it and see where you should go from here :slight_smile:

When I use:

[php]$tweetData = json_decode($tweets);
echo ‘

’;
var_dump($tweetData);
echo ‘
’;[/php]

All I get on screen is NULL.

When I use:

[php]$tweetData = json_encode($tweets);
echo ‘

’;
var_dump($tweetData);
echo ‘
’;[/php]

I get this:

http://www.anxietyclown.com/TwitterO/get_tweets2.php

Progress!! I figured out I have to encode the json then decode it in the var_dump as so:

[php]$tweetData = json_encode($tweets);
echo ‘

’;
var_dump(json_decode($tweetData, true));
echo ‘
’;[/php]

So now I have all my data store in an array called $tweetData, correct? My question is, how do I get to it? I can get it to print on the screen but what I need is to get individual pieces of that data for parsing.

I am bringing the latest 5 tweets into the array, each tweet has a ton of data in it (40-50 fields). I only need 3 or 4 of those pieces of data from each tweet to do the analyzing of the tweet that I need to do.

How do I extract them into variables I can work with?

I tried this:

echo “$tweetData[13]”;

and all it did was return the 13th character of the entire array, rather than the 13th element.

http://www.anxietyclown.com/TwitterO/get_tweets2.php

This is an example of the array in question when it’s been var_dump(ed). I’m asking how to pull individual elements of it into variables.

$tweet1_content
$tweet1_ID
$tweet1_time

and so on.

This should work.
[php]foreach ($tweetData as $tweet) {
echo 'ID: ’ . $tweet[‘id’];
echo 'Created: ’ . $tweet[‘created_at’];
echo 'Content: ’ . $tweet[‘text’];
echo ‘User: ’ . $tweet[‘user’][‘screen_name’] . ’ (’ . $tweet[‘user’][‘id_str’] . ‘)’;
}
[/php]

if you want data from one tweet you could also do
[php]echo $tweetData[0][‘id’];[/php]

You should try playing around with a large array and var dumping the values when you do foreach, echo $array[0], etc. It’s actually really easy.

Ex:

[php]array(5) {
[0]=>
array(22) {
[“created_at”]=>
string(30) “Mon Sep 16 00:10:51 +0000 2013”
[“id_str”]=>
string(18) “379396930235031552”
[“user”]=>
array(39) {
[“id_str”]=>
string(8) “19601213”
[“screen_name”]=>
string(9) “jdroberto”
[“entities”]=>
array(2) {
[“url”]=>
array(1) {
[“urls”]=>
array(1) {
[0]=>
array(4) {
[“url”]=>
string(22) “http://t.co/Y9kUVJgnnF
[“expanded_url”]=>
string(28) “http://www.thehandsondad.com
[“display_url”]=>
string(17) “thehandsondad.com
}
}
}
}
}
[“retweet_count”]=>
int(54)
[“entities”]=>
array(4) {
[“hashtags”]=>
array(1) {
[0]=>
array(2) {
[“text”]=>
string(8) “football”
}
}
}
}
[1]=> …[/php]

If you do a foreach $array, or $array[0] here, then the (first) new value will contain:

[php]array(22) {
[“created_at”]=>
string(30) “Mon Sep 16 00:10:51 +0000 2013”
[“id_str”]=>
string(18) “379396930235031552”
[“user”]=>
array(39) {
[“id_str”]=>
string(8) “19601213”
[“screen_name”]=>
string(9) “jdroberto”
[“entities”]=>
array(2) {
[“url”]=>
array(1) {
[“urls”]=>
array(1) {
[0]=>
array(4) {
[“url”]=>
string(22) “http://t.co/Y9kUVJgnnF
[“expanded_url”]=>
string(28) “http://www.thehandsondad.com
[“display_url”]=>
string(17) “thehandsondad.com
}
}
}
}
}
[“retweet_count”]=>
int(54)
[“entities”]=>
array(4) {
[“hashtags”]=>
array(1) {
[0]=>
array(2) {
[“text”]=>
string(8) “football”
}
}
}[/php]

and you can just follow the three-structure to get the data you want.
[php]echo $tweet[‘created_at’];
echo $tweet[‘user’][‘entities’][‘url’][‘urls’][0]['display_url];[/php]

[php] foreach ($tweetData as $tweet) {
echo 'ID: ’ . $tweet[‘id’];
echo 'Created: ’ . $tweet[‘created_at’];
echo 'Content: ’ . $tweet[‘text’];
echo ‘User: ’ . $tweet[‘user’][‘screen_name’] . ’ (’ . $tweet[‘user’][‘id_str’] . ‘)’;[/php]
}

Doesnt end up echo-ing anything on screen at all. Not sure what I am doing wrong.

Post your updated code, I did this yesterday and it worked fine, must be a small error somewhere.

I am guessing this is it:
[php]$tweetData = json_encode($tweets);
echo ‘

’;
var_dump(json_decode($tweetData, true));
echo ‘
’;[/php]

How did you change this code afterwards? It should look something like this:
[php]$tweetData = json_decode(json_encode($tweets), true);[/php]

Although I still think it’s strange you have to json encode it first. I think I have to look into the twitter api, curious how that response looks.

yes! it was indeed a syntax goof on my part. so I’m in really good shape at this point, moving slowly toward my goal. Here’s where the code stands now. I am going through the cached tweets, displaying only the ID and Text of the tweet and then parsing whether or not it’s a retweet or reply (and echoing that information on screen).

[php]$tweets = $connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=”.$notweets);

$tweetData = json_decode(json_encode($tweets), true);

foreach ($tweetData as $tweet) {
echo '
ID: ’ . $tweet[‘id_str’];
echo '
Tweet: ’ . $tweet[‘text’];

 if ($tweet['retweeted_status'] != NULL) 
{
$retweet = TRUE;
}
else
{
	$retweet = FALSE;
}

if ($tweet['in_reply_to_status_id'] != NULL) 
{
$reply = TRUE;
}
else 
{
$reply = FALSE;
}

echo "<br/>reply ".$reply;
echo "<br/>retweet ".$retweet;

echo “

”;[/php]

If you get any more problems then it’s just to post back :slight_smile:

I’d like to point you in the direction of a short if/else syntax, I like it to keep the code short and consise.

Your code can be rewritten to this:

[php]$tweets = $connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=”.$notweets);

$tweetData = json_decode(json_encode($tweets), true);

foreach ($tweetData as $tweet) {
echo “

”;
echo '
ID: ’ . $tweet[‘id_str’];
echo '
Tweet: ’ . $tweet[‘text’];

$retweet = $tweet[‘retweeted_status’] != NULL ? TRUE : false;
$reply = $tweet[‘in_reply_to_status_id’] != NULL ? TRUE : false;

echo "
reply " . $reply;
echo "
retweet " . $retweet;

echo “

”;
}[/php]

Note how much space is saved with the short if/elses :slight_smile:

Or you could just skip setting the variables alltogether.

[php]$tweets = $connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=”.$notweets);

$tweetData = json_decode(json_encode($tweets), true);

foreach ($tweetData as $tweet) {
echo “

”;
echo '
ID: ’ . $tweet[‘id_str’];
echo '
Tweet: ’ . $tweet[‘text’];
echo "
reply " . $tweet[‘retweeted_status’] != NULL ? TRUE : false;
echo "
retweet " . $tweet[‘in_reply_to_status_id’] != NULL ? TRUE : false;
echo “

”;
}[/php]

Excellent, thank you! I’m a huge fan of elegance in coding even if I’m not capable of it at first site :frowning:

I’m trying to make the next piece of code conditional on both $reweet and $reply being FALSE. Not sure what the most un-convoluted way to do it might be.

Truly appreciate your time and help thus far!

Sorry to ask but could you explain what this code does?

[php]$retweet = $tweet[‘retweeted_status’] != NULL ? TRUE : false;
$reply = $tweet[‘in_reply_to_status_id’] != NULL ? TRUE : false;[/php]

is it a sort of if/else? I read up on booleans but can’t find this example.

As said it’s a short if/else

Basically
Condition ? if true : if false

[php]$result = !empty($_GET[‘data’]) ? $_GET[‘data’] : null;[/php]

If get data is not empty (empty checks for both is set and empty), then result = get data, else result = null.

So what I didnin two lines was exactly the same as you did in 20.

http://robertsettle.com/2012/07/php-shorthand-if-statements/

Wrote the last post on my phone and it wouldn’t let me paste below the text. This should also serve as a warning for possible typos, but i think I got it right ^^

Sponsor our Newsletter | Privacy Policy | Terms of Service