我试图从另一个网站“获取”文本并将其发布到我的网站上,这样当其他网站更新“div”或其他对象内的文本时,我的网站也会更新。
可以在php中完成吗?如果是这样,怎么样?
答案 0 :(得分:2)
php内置函数file_get_contents来执行此操作
$html=file_get_contents("http://www.website.com")
然而,这不是特别有用,你不能在请求上设置超时,所以使用curl快速功能:
function getHTML($url,$timeout)
{
$gs = curl_init($url); // initialize curl with given url
curl_setopt($gs, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent
curl_setopt($gs, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
curl_setopt($gs, CURLOPT_FOLLOWLOCATION, true); // follow redirects
curl_setopt($gs, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds
curl_setopt($gs, CURLOPT_FAILONERROR, 1); // stop if an error is encountered
return @curl_exec($gs);
}
然后您可以使用正则表达式来获取所需的数据,例如
preg_match("/<title>(.*)<\/title>/i", $html, $match);
$pagetitle = $match[1];
修改强>
在回复以下关于Regex的评论时,我建议您查看以下Stack Overflow问题并回答:
因为PHP文档对象模型可能正是您所需要的。
答案 1 :(得分:0)
这个怎么样:
<?php
function getHTMLData($url , $query){
$data = simplexml_load_file($url);
$result = $data->$query;
}
请记住HTML来自XML,浏览器使用这些标记解析