如何在php下载网页

问题描述 投票:9回答:5

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

php parsing webpage
5个回答
15
投票

你可以使用这样的东西

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

11
投票

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

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

当你的PHP启用了allow_url_fopen时。

但基本上,支持HTTP stream wrappers的任何功能都可用于下载页面。


8
投票

随着curl库。


6
投票

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

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

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

你可以做的另一件事。

然后你可以循环通过每一行,如果这符合你的目标:

foreach($array as $line){

    echo $line;
    // do other stuff here

}

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


4
投票

您可以使用此代码

$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;
© www.soinside.com 2019 - 2024. All rights reserved.