PHP:如何将网页内容加载到变量中? [英] PHP: how can I load the content of a web page into a variable?

查看:77
本文介绍了PHP:如何将网页内容加载到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将网页内容加载到变量中?

How can I load the content of a web page into a variable?

我需要将HTML存储在字符串中.

I need to store the HTML in a string.

推荐答案

file_get_contents :

Provided allow_url_fopen is enabled, you can just use 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_create manual page where a couple of HTTP-headers are set.


如果禁用了allow_url_fopen,则另一种解决方案是使用
curl -但这意味着多几行代码.


If allow_url_fopen is disabled, another solution is to work with curl -- means a couple more lines of code, though.

在最简单的情况下,这种基本的事情应该起作用:

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_setopt for a complete list.

例如:

  • 我经常设置 CURLOPT_FOLLOWLOCATION ,因此遵循重定向.
  • 与tiemout相关的选项通常也很有用.

这篇关于PHP:如何将网页内容加载到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆