我想在PHP中检索链接(网页)的HTML代码.例如,如果链接是
然后我想要提供的页面的HTML代码.我想检索此HTML代码并将其存储在PHP变量中.
我怎样才能做到这一点?
Gre*_*reg 121
如果您的PHP服务器允许url fopen包装器,那么最简单的方法是:
$html = file_get_contents('http://stackoverflow.com/questions/ask');
Run Code Online (Sandbox Code Playgroud)
如果您需要更多控制,那么您应该查看cURL函数:
$c = curl_init('http://stackoverflow.com/questions/ask');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)
$html = curl_exec($c);
if (curl_error($c))
die(curl_error($c));
// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
Run Code Online (Sandbox Code Playgroud)
Ick*_*und 12
您可能想要查看来自Yahoo的YQL库:http://developer.yahoo.com/yql
手头的任务很简单
select * from html where url = 'http://stackoverflow.com/questions/ask'
Run Code Online (Sandbox Code Playgroud)
您可以在控制台中尝试此操作:http://developer.yahoo.com/yql/console(需要登录)
另请参阅Chris Heilmanns的截屏视频,了解更多您可以做的更多信息:http://developer.yahoo.net/blogs/theater/archives/2009/04/screencast_collating_distributed_information.html
简单方法:使用file_get_contents():
$page = file_get_contents('http://stackoverflow.com/questions/ask');
Run Code Online (Sandbox Code Playgroud)
请注意,allow_url_fopen必须是true在你php.ini能够使用URL的fopen封装.
更高级的方法:如果您无法更改PHP配置,allow_url_fopen则false默认情况下如果安装了ext/curl,请使用该cURL库连接到所需的页面.
这是从 URL 获取内容的两种不同的简单方法:
1)第一种方法
从您的主机(php.ini 或其他地方)启用Allow_url_include
<?php
$variableee = readfile("http://example.com/");
echo $variableee;
?>
Run Code Online (Sandbox Code Playgroud)
或者
2)第二种方法
启用 php_curl、php_imap 和 php_openssl
<?php
// you can add anoother curl options too
// see here - http://php.net/manual/en/function.curl-setopt.php
function get_dataa($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$variableee = get_dataa('http://example.com');
echo $variableee;
?>
Run Code Online (Sandbox Code Playgroud)
您也可以使用 DomDocument 方法来获取单独的 HTML 标记级别变量
$homepage = file_get_contents('https://www.example.com/');
$doc = new DOMDocument;
$doc->loadHTML($homepage);
$titles = $doc->getElementsByTagName('h3');
echo $titles->item(0)->nodeValue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
271490 次 |
| 最近记录: |