从其他网站检索数据的最佳方法是什么?

时间:2013-01-23 23:32:51

标签: php xml curl file-get-contents

我想从其他网站获取一张桌子(该表每天都在更新),我希望它能够在我的网站上显示,而不是与原网站中的相同。

所以我使用curl和strstr()得到了表,但是使用字符串函数编辑整个表似乎毫无意义。我相信这样做会更容易。

也许有办法以xml格式创建原始表格,我可以更容易地使用结构?

非常感谢!

1 个答案:

答案 0 :(得分:0)

下面是一个粗略的示例,说明如何使用表(仅用于回显另一个表),下面我使用SimpleXML和xpath在文档中搜索具有表数据类的元素并循环遍历所有TR和一些特殊条件来处理存在的块和

明显的缺点是,如果第三方网站的布局发生变化,您的代码将停止运作。

header('Content-Type: text/html; charset=UTF-8');
$html = file_get_contents('http://www.votes-19.gov.il/nationalresults'); // or use curl
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); 

$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);

echo '<!doctype html><html><head><style type="text/css">body{direction: rtl;}</style></head><body><table>';
if($trxpath = $xml->xpath('//table[@class="TableData"]/tr'))
{
  foreach($trxpath as $tr)
  {
    echo '<tr>';
    echo '<th>' . $tr->th . '</th>';
    foreach($tr->td as $td)
    {
      if($td->div)
        echo '<td>' . $td->div . '</td>';
      else
        echo '<td>' . $td . '</td>';
    }
    echo '</tr>';
  }
}
echo '</table></body></html>';