【问题标题】:How to get contents of a webpage with PHP如何使用 PHP 获取网页的内容
【发布时间】:2017-12-05 16:38:22
【问题描述】:

我正在使用 PHP 来管理我的 Telegram Bot。基本上 Telegram 添加了一个功能,可以让用户在这个 url 中从他们的机器人获取更新:

https://api.telegram.org/bot[TOKEN_NUMBER]

现在我想知道,我要搜索的机器人是否存在。

因此,每当您输入错误的机器人令牌编号时,API 页面都会返回:

{"ok":false,"error_code":401,"description":"Unauthorized"}

如果存在,则页面返回:

{"ok":true,"result":[]}

如您所见,我必须获取此页面的内容并确定一些变量才能知道机器人的存在。那么,我怎样才能用 PHP 做到这一点呢?

【问题讨论】:

标签: php telegram-bot php-telegram-bot


【解决方案1】:

你可以使用:

$content = file_get_contents($url);

或使用 cURL http://php.net/manual/en/curl.examples-basic.php

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

【讨论】:

  • 很好,但现在我测试了这个$ch = curl_init("https://api.telegram.org/bot".$token."/getUpdates");,而不是写{"ok":false,"error_code":409,"description":"Conflict: can't use getUpdates method while webhook is active"}(这是我的机器人更新的当前状态),它写道:{"ok":false,"error_code":404,"description":"Not Found"}
  • 尝试 echo/var_dump 你的 url 字符串,它的格式是否正确?有没有遗漏/
【解决方案2】:

尝试使用 file_get_contents(),它会返回您在浏览器中打开相同 URL 时看到的任何内容。你也可以看看Composer packages这样做,这样你就不必再发明轮子了;)

【讨论】:

    【解决方案3】:

    使用get_headers快速简单的两个班轮

    $headers=get_headers('https://api.telegram.org/bot/12345');
    $active=$headers[0]=='HTTP/1.1 404 Not Found' ? false : true;
    

    然后您可以在布尔逻辑测试中使用$active 来继续处理或中止。

    if( $active ){/* do stuff */} else {/* go to the pub */}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 2010-11-06
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      相关资源
      最近更新 更多