获取权限
如果您需要抓取远程页面,您应该首先确保您没有做任何非法的事情。我无法就你想做的事情的合法性向你提供咨询,但我可以肯定地说,有些人不喜欢他们的数据被废弃——你真的应该与网站管理员核实一下如果他们对此有任何问题。
获得许可?好...
当你被清除后,考虑使用 DOMDocument 类在一系列嵌套对象中创建 DOM 的表示,你可以与这些对象进行非常简单的交互:
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents("http://foo.com/data/statistics"));
如果您完全熟悉 JavaScript 中的 DOM 遍历和选择方法,那么DOMDocument 接口似乎非常熟悉。为了通过 ID 获取特定元素,您可以使用适当的方法:
$statistics = $doc->getElementById("statistics");
并在 that 元素中获取所有 TD 元素:
$cells = $statistics->getElementsByTagName("td");
无需过多赘述,您可以继续使用DOMDocument类提供给您的方法来遍历和选择数据。当您到达您正在寻找的实际节点时,您可以轻松地将它们的值保存到一个数组中,然后将该数组输出为带有一些 JavaScript 的字符串以显示 Google 图。
做个好人!
缓存此操作的结果是明智的,这样您就不会在每次脚本运行时都访问远程服务器。将输出保存到带有时间戳的本地文件,并检查该时间戳是否过期 - 当它过期时,将其删除,并在其位置创建一个新的缓存结果。
这可能是什么样子
这里是您的解决方案完成后可能类似于的一个非常基本的实现。请注意,我们最多每天只访问远程服务器一次。
// Silence errors due to malformed HTML
libxml_use_internal_errors(true);
// This function builds out data out, when necessary
function build_output () {
// Create a DOMDocument, grab debt-clock HTML
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents("http://brillig.com/debt_clock/"));
// Find element representing total National Debt
$total = $doc->getElementsByTagName("img")->item(0);
// Grab value from the alt attribute
$total = $total->attributes->getNamedItem("alt")->nodeValue;
// Second paragraph has two more values of interest
$parag = $doc->getElementsByTagName("p")->item(1);
// Build out resulting array of data: Natl. Debt, Population, Ind. Debt
$data = Array(
"ntl" => str_replace(" ", "", $total),
"pop" => $parag->getElementsByTagName("b")->item(0)->nodeValue,
"pay" => $parag->getElementsByTagName("b")->item(1)->nodeValue
);
// Return a JSON string of this data
return json_encode($data);
}
// Most recent cache file (today)
$cache_name = date("Y-m-d");
if (!file_exists($cache_name)) {
// Today's cache doesn't exist, create it.
$output = build_output();
$message = "Fresh: " . $output;
file_put_contents($cache_name, $output);
} else {
// Today has already been cached, load it.
$message = "Cached: " . file_get_contents($cache_name);
}
// Show the user the output
echo $message;
从缓存加载时,上述脚本的输出类似于:
Cached: {
"ntl":"$16,293,644,693,599.87",
"pop":"313,929,808",
"pay":"$51,902.19"
}
您现在可以将该 JSON 数据加载到您喜欢的任何服务中,以生成表示其数据的图像。