如何使用PHP获取网页内容

时间:2017-12-05 08:17:42

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

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

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

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

因此,无论何时键入机器人的错误令牌号,API页面都会返回:

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

如果存在,页面将返回此内容:

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

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

3 个答案:

答案 0 :(得分:4)

你可以使用:

$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);
?>

答案 1 :(得分:1)

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

答案 2 :(得分:0)

使用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 */}