2011-02-14 21 views
0

檢索跨度ID內的值?在PHP中從其他站點檢索值?

<span id="playerCount">157,767 people currently online</span> 

我該如何去獲取該ID內的值?我想到了preg_match(),但是這是安全的嗎?

+0

壞主意,這意味着你的網頁渲染時間將是`原來的頁面渲染時間+外部網站的渲染時間+網絡延遲' – ajreal 2011-02-14 05:53:13

回答

4

使用php的DOM方法。以下代碼假設您已啓用allow_url_fopen:

$domd = new DOMDocument(); 
libxml_use_internal_errors(true); 
$domd->loadHTML(file_get_contents($url)); 
libxml_use_internal_errors(false); 

$span = $domd->getElementById("playerCount"); 
$span_contents = $span->textContent; 
+1

這是否依賴於網站正常形成壽? – Jacob 2011-02-14 06:11:49

0

使用正則表達式,這是可能的,而且非常容易。如果是一些更高級的我立即建議使用解析HTML創建工具(請參閱DOM文檔)

<?php 
// content containing: '<span id="playerCount">157,767 people currently online</span>'; 
$content = file_get_contents('http://example.com'); 
preg_match('/<span id="playerCount">([0-9,]+) people currently online<\/span>/', $content, $matches); 
var_dump($matches);