问题
<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "HIDDEN FOR STACK ASSIST",
'oauth_access_token_secret' => "HIDDEN FOR STACK ASSIST",
'consumer_key' => "HIDDEN FOR STACK ASSIST",
'consumer_secret' => "HIDDEN FOR STACK ASSIST"
);
// Your specific requirements
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=#trekconspringfield&result_type=recent';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($response, true); //tried with and without true - throws class error without it.
foreach($response as $tweet)
{
$url = $tweet['entities']['urls'];
$hashtag = $tweet['entities']['hashtags'];
$text = $tweet['text'];
echo "$url <br />";
echo "$hashtag <br />";
echo "$text <br />";
echo "<br /><br />";
}
echo "<pre>". var_dump($response) ."</pre>";
?>
When I run this code it gets data in the response but when I try parsing it to separate the data into something useful it shows as blank. I have been through almost all PHP JSON and Twitter tag answers on here and tried almost all of them with no success. Sending to the Code God's for answers. Thank you.
Page where it is currently uploaded to... http://trekconspringfield.com/twitter.php
回答1:
$response
contains two entries: statuses
and search_metadata
. You probably want to iterate through statuses
, so you should loop like this:
foreach($response['statuses'] as $tweet)
{
$text = $tweet['text'];
}
The next problem you will face with this code is $url
and $hashtag
- they are arrays so you can't just echo
them, you have to iterate and gather only relevant info to echo.
And one more thing:
echo "<pre>". var_dump($response) ."</pre>";
var_dump
does not return anything, so it can not be concatenated to <pre>
. To have readable output, use it like this:
echo "<pre>";
echo var_dump($response);
echo "</pre>";
回答2:
If you look at the $response
, you will see that you are accessing it the wrong way.
I've looked at some of the data, and it's formatted like this:
array(
"statuses" => array(
array(
// some stuff
"text" => "#trekconspringfield Springfield is the place to be now and on May 9th 2014!",
"user" => array( /* some stuff */ )
),
array(
// some stuff
"text" => "#trekconspringfield rocks",
"user" => array( /* some stuff */ )
),
array(
// some stuff
"text" => "#trekconspringfield",
"user" => array( /* some stuff */ )
),
)
);
To get exact structure, array indices etc, you will have to inspect it with print_r()
, because var_dump()
adds too much useless garbage to the output.
来源:https://stackoverflow.com/questions/18038526/php-twitter-hashtag-search-showing-no-results-in-parse-but-data-present-in-array