gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:13 26 4
gpt4 key购买 nike

我曾经听说这可以使用 Curl 来完成,但我不想在我的站点上显示来自外部站点的所有内容,而只想显示来自特定 div 的内容。如何做到这一点?

最佳答案

您可以使用 PHP Simple DOM Parser抓取页面并轻松选择其中的部分。

简单到:

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

文档 here .

如果你想做的是抓取 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;

?>

这有点老套,因为我使用 cURL 抓取页面,然后需要将它存储在某个地方,以便 PHP Simple HTML Dom 解析器能够正确解析它,但它确实有效。

关于php - 如何使用 PHP 在一个站点上显示另一个站点的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2734136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com