PHP:如何将网页内容加载到变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3249157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: how can I load the content of a web page into a variable?
提问by aneuryzm
How can I load the content of a web page into a variable?
如何将网页内容加载到变量中?
I need to store the HTML in a string.
我需要将 HTML 存储在一个字符串中。
回答by Pascal MARTIN
Provided allow_url_fopenis enabled, you can just use file_get_contents:
如果allow_url_fopen已启用,您只需使用file_get_contents:
$my_var = file_get_contents('http://yoursite.com/your-page.html');
And, if you need more options, take a look at Stream Functions-- there is an example on the stream_context_createmanual page where a couple of HTTP-headers are set.
而且,如果您需要更多选项,请查看Stream Functions-stream_context_create手册页上有一个示例,其中设置了几个 HTTP 标头。
If allow_url_fopenis disabled, another solution is to work with curl-- means a couple more lines of code, though.
如果allow_url_fopen被禁用,另一种解决方案是使用curl——不过,意味着多几行代码。
Something as basic as this should work in the simplest situations :
像这样基本的东西应该在最简单的情况下工作:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$my_var = curl_exec($ch);
curl_close($ch);
But note that you might need some additional options -- see the manual page of curl_setoptfor a complete list.
但请注意,您可能需要一些其他选项——请参阅 的手册页以curl_setopt获取完整列表。
For instance :
例如 :
- I often set
CURLOPT_FOLLOWLOCATION, so redirects are followed. - The tiemout-related options are quite often useful too.
- 我经常设置
CURLOPT_FOLLOWLOCATION,所以会遵循重定向。 - 与 tiemout 相关的选项通常也很有用。
回答by SwR
The code below stores the content of the site w3schools.com into a variable.
下面的代码将站点 w3schools.com 的内容存储到一个变量中。
$my_var = file_get_contents('http://www.w3schools.com');
echo $my_var;

