2012-10-30 99 views
3

我正在接近網絡編程。我需要從網頁中檢索一些信息。我有頁面的url,所以我想要html源代碼,將它翻譯成xml,然後使用php的dom函數來獲取我需要的信息。Php - 從XML文件檢索信息

我的PHP代碼是這樣的:

$url=$_POST['url']; //url 

$doc_html=new DOMDocument(); 
$doc_html->loadHTML($url); //html page 
$doc_xml=new DOMDocument(); 
$doc_xml->loadXML($doc_html->saveXML()); //xml converted page 

$nome_app=new DOMElement($doc_xml->getElementById('title')); 

echo $nome_app->nodeValue; 

我得到這個致命的錯誤:

Uncaught exception 'DOMException' with message 'Invalid Character Error' on this line:

$nome_app=new DOMElement($doc_xml->getElementById('title')); 

有什麼不對?它是整個過程html-to-xml嗎?我在網上找到了一些例子,並應該工作... 謝謝!

回答

1

我會去一個preg_match()解決方案來獲取所需的內容通過解析整個文檔作爲XML。特別是如果文件由於某種原因失效,您將無法再獲取您的信息。

+0

你和@Bgi是正確的,但這是我的情況:我有一個巨大的源代碼,我不知道XML文件需要的DTD。解析和糾正整個文檔是沒有用的,因爲我只需要一些html內容,並且可以在不解析很長的字符串的情況下檢索這些內容,因此可以使用DOM。 – esseara

2

解決了!簡單地說:

$doc_html=new DOMDocument(); 
$doc_html->loadHTML(file_get_contents($url)); 
$doc_html->saveXML(); 
$nome = $doc_html->getElementsByTagName('h1'); 
foreach ($nome as $n) { 
    echo $n->nodeValue, PHP_EOL; 
} 

也許代碼太亂了。 謝謝大家的答案!