-1

谢谢 !

在 php 中,我想知道是否存在 twitter 用户。为此,我尝试恢复 url 的内容:

$json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$_GET['search']);
$jsonObject = json_decode($json);

其中 $_GET['search'] = 是在 URL 中传递的用户名。

但问题是,如果有人给出一个不存在的用户名,我会得到一个错误。

在 php.net 上,他们说如果出现错误,file_get_contents 将返回 false。

我试图在一个条件下做:

if(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$_GET['search']) != false){
    // do my stuff 
}
else{
    // say that this username don't exists
}

但是当我尝试这段代码时,我得到了一个橙色的大警告代码,上面写着:

Warning: file_get_contents(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=A_Wrong_User_Name) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP

所以我可以删除错误并检查 twitter 用户是否存在。如果他存在,我想用 file_get_contents 获取页面的内容,如果不存在,我想显示该用户不存在。

感谢帮助 !

4

1 回答 1

0

您应该使用 CURL 而不是file_get_contents

<?php
 $username = "user";

 $url="http://api.twitter.com/1/users/show/".$username.".xml";

 $ch = curl_init();
 curl_setopt ($ch, CURLOPT_URL, $url);
 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
 curl_setopt($ch, CURLOPT_NOBODY, 1);
 curl_setopt($ch, CURLOPT_HEADER, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

 curl_exec($ch);
 $header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);

 if( $header == "404" )
 {
 //it does not exist
 }else{
 //it exists
 }
于 2012-05-04T12:18:47.573 回答