HTML解析器到网站图表

时间:2012-11-24 12:51:03

标签: php html web

因此,有一个网站,他们有一些关于该网站的统计数据,并且每天更新。我想要做的是废弃该网站并将这些信息检索到我的网站并将它们放入折线图中。像http://code.google.com/apis/ajax/playground/?type=visualization#line_chart这样的东西 或这些http://code.google.com/apis/ajax/playground/?type=visualization#image_line_chart 唯一的问题是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

获得许可

如果您需要抓取远程页面,首先应该确保您没有做任何违法行为。我无法向你咨询你想要做的事情的合法性,但我可以肯定地说有些人不喜欢他们的数据被废弃 - 你真的应该检查网站管理员看看如果他们有任何问题。

获得许可?好...

当你被清除时,考虑使用DOMDocument类在一系列嵌套对象中创建DOM的表示,这些对象可以非常简单地进行交互:

$doc = new DOMDocument();
$doc->loadHTML(file_get_contents("http://foo.com/data/statistics"));

如果您完全熟悉JavaScript中的DOM遍历和选择方法,那么DOMDocument界面就会非常熟悉。为了通过ID获取特定元素,您将使用适当的方法:

$statistics = $doc->getElementById("statistics");

并获取 元素中的所有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数据加载到您现在喜欢的任何服务中,以生成表示其数据的图像。