Php - 从xml文件中检索信息

时间:2012-10-30 10:23:31

标签: php html xml dom

我正在接近网络编程。我需要从网页中检索一些信息。我有页面的url,所以我想要html源代码,将其翻译成xml,然后使用php的dom函数获取我需要的信息。

我的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;

我得到了这个致命的错误:

  

此行上带有“无效字符错误”消息的未捕获异常“DOMException”:

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

怎么了?是整个过程html-to-xml?我在网上找到了一些例子,应该可以... 谢谢!

4 个答案:

答案 0 :(得分: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;
}

以前的代码可能太乱了。 谢谢大家的答案!

答案 1 :(得分:1)

您需要为HTML中使用的特殊字符定义XML实体。 它必须与此处的问题相同:DOMDocument::loadXML vs. HTML Entities

答案 2 :(得分:1)

我会选择preg_match()解决方案来获取将整个文档解析为XML所需的内容。特别是如果文档由于某种原因变得无效,您将不再获得您的信息。

答案 3 :(得分:0)

最好的方法是使用xpath查询,

http://php.net/manual/en/simplexmlelement.xpath.php

非常快