2012-10-30 100 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; 
} 

也许代码太乱了。 谢谢大家的答案!