php 如何获取远程 HTML 页面的内容

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

How to get Content of Remote HTML page

phphtml

提问by lilruchira

I want to get remote html contents that on "li" that with a spacific Class name and Children of em using divs.

我想获取“li”上的远程 html 内容,该内容具有空间类名称和使用 div 的 em 的子项。

My remote content is Like this

我的远程内容是这样的

<ul>

<li class="user">

<div class="name">My Name 1</div>

<div class="rep">20</div>

</li>

<li class="user">

<div class="name">My Name 2</div>

<div class="rep">23</div>

</li>

<li class="user">

<div class="name">My Name 3</div>

<div class="rep">40</div>

</li>

</ul>

<ul>

<li class="user">

<div class="name">我的名字1</div>

<div class="rep">20</div>

</li>

<li class="user">

<div class="name">我的名字2</div>

<div class="rep">23</div>

</li>

<li class="user">

<div class="name">我的名字3</div>

<div class="rep">40</div>

</li>

</ul>

After get their data it must be like this.

拿到他们的数据后一定是这个样子。

[My Name 1,20]

[My Name 2,23]

[My Name 3,40]

[我的名字 1,20]

[我的名字 2,23]

[我的名字 3,40]

Thanks.

谢谢。

Sorry for the My Poor English

对不起我可怜的英语

Note : Have more content than this on remote page.

注意:在远程页面上有比这更多的内容。

回答by verisimilitude

Use CURL to read the remote URL to fetch the HTML.

使用 CURL 读取远程 URL 以获取 HTML。

$url = "http://www.example.com";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);

Then use PHP's DOM object modelto parse the HTML.

然后使用PHP 的 DOM 对象模型来解析 HTML。

For example to fetch all <h1>tags from the source,

例如<h1>从源中获取所有标签,

$DOM = new DOMDocument;
$DOM->loadHTML( $output);

//get all H1
$items = $DOM->getElementsByTagName('h1');

//display all H1 text
 for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";