使用json_decode从twitter feed中提取字段

时间:2013-08-01 17:35:20

标签: php json twitter

我正在尝试使用以下代码获取我的Twitter Feed:

// Make the request and get the response into the $json variable
$json =  $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();

// It's json, so decode it into an array
$result = json_decode($json);

// Access the profile_image_url element in the array
echo $result->created_at;
?>

我得到的结果是:

Thu Oct 25 18:40:50 +0000 2012

如果我尝试使用以下内容获取文字:

echo $result->text;

我收到此错误:

Notice: Undefined property: stdClass::$text in /Library/WebServer/Documents/include/twitter_noformat/items.php on line 35 

我的数据格式的部分var_dump包括:

{"created_at":"Thu Aug 01 16:12:18 +0000 2013",
"id":362969042497175553,
"id_str":"362969042497175553",
"text":"A warm welcome to our new international students from China, Hong Kong and Germany! http:\/\/t.co\/GLvt3GynJV",
"source":"web",
"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,"user":

我的问题是: created_at给了我一个值。 id给了我一个价值。为什么不发短信?我对JSON btw一无所知。我不是一个非常高级的程序员,但模式看起来和我一样。

编辑:我发现了一个很酷的片段,将我的推特数组转换为更具可读性的内容。功能如下:

// It's json, so decode it into an array
$result = json_decode($json);

// Access the profile_image_url element in the array
$pretty = function($v='',$c="&nbsp;&nbsp;&nbsp;&nbsp;",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'&lt;NULL&gt;':"<strong>$v</strong>");}return$r;};

echo $pretty($result);

结果现在看起来像这样:

statuses_count: 583
lang: en
status:
    created_at: Thu Aug 01 21:10:10 +0000 2013
    id: 363044004444651522
    id_str: 363044004444651522
    text: @CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw

这很奇怪,因为这会使文本看起来像是对象的一部分?

我已经确定twitter会踢回一系列对象。那些对象可以有很多项目(?)正如我之前提到的,虽然我可以回显$ result-&gt; created_at;但不是文字。它们都在阵列的同一级别。

提前感谢您的帮助, 多诺万

1 个答案:

答案 0 :(得分:1)

经过一天的研究后,这是我的解决方案:

$result = json_decode( $json );
echo "Text:" . $result->status->text . "<br />";

文字是状态的孩子(?)。我可以回显created_at,因为它是在数组的两个级别使用的,这是我之前从未见过的。我想,文本在状态对象内。

created_at: Thu Oct 25 18:40:50 +0000 2012
favourites_count: 1
utc_offset: -25200
time_zone: Pacific Time (US & Canada)
geo_enabled: 1
verified:
statuses_count: 583
lang: en
status:
     created_at: Thu Aug 01 21:10:10 +0000 2013
     id: 363044004444651522
     id_str: 363044004444651522
     text: @CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw