如何使用PHP在一个站点上显示内容?

Jam*_*mes 4 php

我曾经听说过这可以使用Curl完成,但我不想显示我网站上外部网站的所有内容,只显示特定div中的内容.如何才能做到这一点?

Ore*_*iya 9

您可以使用PHP Simple DOM Parser来抓取页面并轻松选择部分页面.

一样容易:

$html = file_get_html('http://www.google.com/');
$ret = $html->find('div[id=foo]'); 
Run Code Online (Sandbox Code Playgroud)

文档在这里.

如果你想要做的是抢的头http://www.freeoh.net/,下面的代码将正常工作.您需要将simple_html_dom.php和一个名为page.txt(确保脚本有权限读取和写入)在同一文件夹下面的脚本.(我假设您已经启用了cURL,正如您在问题中提到的那样.)

<?php

include 'simple_html_dom.php';

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://www.freeoh.net/");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_REFERER, "http://www.freeoh.net/");

$result = curl_exec ($curl);
curl_close ($curl);
//write contents of $result to file
$File = "page.txt";
$fh = fopen($File, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);
//turn file into dom object
$page = file_get_html("page.txt");
$header = $page->find("div", 1);
echo $header;

?>
Run Code Online (Sandbox Code Playgroud)

这有点hacky,因为我使用cURL来抓取页面,然后需要将它存储在某处,以便PHP Simple HTML Dom解析器可以正确解析它,但它可以正常工作.