使用PHP和cURL抓取Twitter好友Feed

时间:2010-08-07 03:14:52

标签: php xml curl twitter

因此,根据我的上一个问题,我正在努力从Twitter上抓取朋友的信息。我按照教程来编写这个脚本,一步一步,所以我不确定它有什么问题,我没有看到任何错误消息。在从shell中保存之前我从未真正使用过cURL,而且我对PHP非常陌生,所以请耐心等待。

<html>
<head>
<title>Twitcap</title>
</head>
<body>
<?php
  function twitcap()
  {
    // Set your username and password
    $user = 'osoleve';
    $pass = '****';

    // Set site in handler for cURL to download
    $ch = curl_init("https://twitter.com/statuses/friends_timeline.xml");

    // Set cURL's option
    curl_setopt($ch,CURLOPT_HEADER,1); // We want to see the header
    curl_setopt($ch,CURLOPT_TIMEOUT,30); // Set timeout to 30s
    curl_setopt($ch,CURLOPT_USERPWD,$user.':'.$pass); // Set uname/pass
    curl_setopt($ch,CURLOPT_RETURNTRANSER,1); // Do not send to screen

    // For debugging purposes, comment when finished
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);

    // Execute the cURL command
    $result = curl_exec($ch);

    // Remove the header
    // We only want everything after <?
    $data = strstr($result, '<?');

    // Return the data
    $xml = new SimpleXMLElement($data);
    return $xml;
  }

  $xml = twitcap();
  echo $xml->status[0]->text;
?>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

在“?&gt;”之后你真的不需要一切吗? ?

$data = strstr($result,'?>');

另外,您使用的是免费的网络主机吗?我曾经遇到过一个问题,即我的托管服务提供商阻止了人们发送垃圾邮件的访问权。

答案 1 :(得分:0)

请注意,如果使用strstr,则returend字符串实际上将包含针串。所以你必须从字符串中删除前两个字符

我宁愿推荐函数substr和strpos的组合!

不管怎样,我认为simplexml应该能够处理这个标题,这意味着我认为这一步不是必需的!

此外,如果我打开网址,我看不到像标题!如果strstr没有找到它返回false的字符串,那么你当前脚本中没有任何数据

代替$data = strstr($result, '<?');试试这个:

if(strpos('?>',$data) !== false) {
$data = strstr($result, '?>');
} else {
$data = $result;
}