2012-06-06 93 views
0
內檢索HTML從URL字符串

我已經撿位和代碼段,你可以看到大概什麼,我試圖做的,顯然,這並不工作,是完全錯誤的:PHP中使用DOM文檔

<?php 

$dom= new DOMDocument(); 
$dom->loadHTMLFile('http://example.com/'); 
$data = $dom->getElementById("profile_section_container"); 
$html = $data->saveHTML(); 
echo $html; 

?> 

使用捲曲打電話,我能夠檢索文檔的URL來源:

function curl_get_file_contents($URL) 
{ 
$c = curl_init(); 
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($c, CURLOPT_URL, $URL); 
$contents = curl_exec($c); 
curl_close($c); 

if ($contents) return $contents; 
else return FALSE; 
} 

$f = curl_get_file_contents('http://example.com/'); 
echo $f; 

所以,我怎樣才能用這個現在實例化一個PHP DOMDocument對象,並提取使用的getElementById

節點
+1

那麼問題是什麼?什麼不行?任何錯誤? – kapa

+1

請注意,如果您的HTML不包含doctype聲明,那麼getElementById將始終返回null。 – Motes

回答

1

這是代碼,你需要避免任何不良HTML錯誤:

$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTMLFile('http://example.com/'); 
$data = $dom->getElementById("banner"); 
echo $data->nodeValue."\n" 

要轉儲整個HTML源代碼,您可以撥打:

echo $dom->saveHTML(); 
+1

這個解決方案是檢索內容,但是我失去了源代碼中的所有html標籤。 –

+0

我沒有得到它,丟失HTML標籤?該代碼只是獲得具有給定ID的DOM元素的值並打印其**文本值**。此外,您可以使用'$ dom-> saveHTML();'轉儲整個HTML。 – anubhava

+0

請修改您的源代碼 –

0

試試這個:

$dom= new DOMDocument(); 
$dom->loadHTMLFile('http://example.com/'); 
$data = $dom->getElementById("profile_section_container")->item(0); 
$html = $data->saveHTML(); 
echo $html; 
+0

請參閱使用curl調用成功檢索字符串來編輯bc im。 –

1

我不知道,但我記得有一次,我想利用這個我是unbale加載一些外部URL作爲文件,因爲在php.ini directve allow-url-fopen被設置爲關閉.. 。

所以檢查pnp.ini或嘗試打開網址的fopen,看看你是否可以讀取URL作爲文件

<?php 
$f = file_get_contents(url); 
var_dump($f); // just to see the content 
?> 

問候;

mimiz

+0

請參閱使用curl調用成功檢索字符串來編輯bc im。 –

0
<?php 

$f = curl_get_file_contents('http://example.com/') 

$dom = new DOMDocument(); 
@$dom->loadHTML($f); 
$data = $dom->getElementById("profile_section_container"); 
$html = $dom->saveHTML($data); 
echo $html; 

?> 

,如果你提供的示例HTML這將有助於。

+0

使用此代碼,我收到錯誤: DOMDocument :: loadHTMLFile():意外的結束標記:http://example.com中的腳本。 但是,我無法透露網址。 –

+0

根據您的更新: DOMDocument :: loadHTML():意外的結束標記:實體中的腳本,行:19 –

+0

loadhtmlfile現在不在我的代碼中。我只是指出saveHTML()接受一個可選參數來限制它到一個特定的domnode。應該從DOMDocument調用saveHTML(),並將domnode保存爲可選參數。 – Motes

0

我想,現在你可以使用DOMDocument::loadHTML 也許你應該嘗試文檔類型的存在(用正則表達式),然後在必要時添加它,爲是一定要把它宣佈... 問候

Mimiz

+0

我該如何去做這件事? –