php 如何在php中下载网页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3062050/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:35:02  来源:igfitidea点击:

How to download a webpage in php

phpparsingwebpage

提问by Hugo

I was wondering how I could download a webpage in php for parsing?

我想知道如何在 php 中下载网页进行解析?

回答by DimitrisD

You can use something like this

你可以使用这样的东西

$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

回答by Gordon

Since you will likely want to parse the page with DOM, you can load the page directly with:

由于您可能希望使用DOM解析页面,因此您可以直接使用以下命令加载页面:

$dom = new DOMDocument;
$dom->load('http://www.example.com');

when your PHP has allow_url_fopenenabled.

当您的 PHP启用了allow_url_fopen 时

But basically, any function that supports HTTP stream wrapperscan be used to download a page.

但基本上,任何支持HTTP 流包装器的函数都可用于下载页面。

回答by Quentin

With the curllibrary.

使用curl库。

回答by RetroNoodle

Just to add another option because it is there, while not the best is just to use file. Its another option that I dont see anyone has listed here.

只是添加另一个选项,因为它在那里,而不是最好的只是使用文件。这是我没有看到任何人在此处列出的另一种选择。

$array = file("http://www.stackoverflow.com");

Its nice if you want it in an array of lines, whereas the already mentioned file_get_contents will put it in a string.

如果你想要它在一个行数组中它很好,而已经提到的 file_get_contents 将它放在一个字符串中。

Just another thing you can do.

只是你可以做的另一件事。

Then you can loop thru each line if this matches your goal to do so:

然后,如果这符合您的目标,您可以遍历每一行:

foreach($array as $line){

    echo $line;
    // do other stuff here

}

This comes in handy sometimes when certain APIs spit out plain text or html with a new entry on each line.

有时当某些 API 吐出纯文本或 html 时,这会派上用场,每行都有一个新条目。

回答by User123

You can use this code

您可以使用此代码

$url = 'your url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
// you can do something with $data like explode(); or a preg match regex to get the exact information you need
//$data = strip_tags($data);
echo $data;