如何使用PHP的DOM解析器从XML中提取节点属性

问题描述:

我从来没有真正使用过DOM解析器,现在我有一个问题。如何使用PHP的DOM解析器从XML中提取节点属性

我怎么会去从这个标记提取的网址:

<files> 
    <file path="http://www.thesite.com/download/eysjkss.zip" title="File Name" /> 
</files> 

使用SimpleXML:

$xml = new SimpleXMLElement($xmlstr); 
echo $xml->file['path']."\n"; 

输出:

http://www.thesite.com/download/eysjkss.zip 
+4

只要小心。 $ xml-> file ['path']的值不是一个字符串。它是SimpleXMLElement的一个实例。 – mellowsoon 2010-10-22 02:28:23

+2

确实。它可能会导致问题时,将值与另一个字符串进行比较,但您可以预先将此值转换为字符串'(字符串)$ xml->文件['路径']' – 2010-10-22 02:40:16

+0

感谢球员,正是我正在寻找 – 2010-10-22 02:49:09

你可以使用PHP简单的HTML DOM解析器,这是一个php库.http://simplehtmldom.sourceforge.net/

+0

为什么在内置功能足够完成此任务时引入第三方库? – Phil 2010-10-22 02:40:49

+0

这就像jquery,非常方便 – Sam 2010-10-22 02:44:23

+1

建议第三方替代[SimpleHtmlDom](http://simplehtmldom.sourceforge.net/),实际使用[DOM](http://php.net/manual/en/book。 dom.php)而不是字符串分析:[phpQuery](http://code.google.com/p/phpquery/),[Zend_Dom](http://framework.zend.com/manual/en/zend.dom .html),[QueryPath](http://querypath.org/)和[FluentDom](http://www.fluentdom.org)。 – Gordon 2010-10-22 10:32:50

要与DOM做到这一点,你做

$dom = new DOMDocument; 
$dom->load('file.xml'); 
foreach($dom->getElementsByTagName('file') as $file) { 
    echo $file->getAttribute('path'); 
} 

您还可以使用XPath做到这一点:

$dom = new DOMDocument; 
$dom->load('file.xml'); 
$xPath = new DOMXPath($dom); 
foreach($xPath->evaluate('/files/file/@path') as $path) { 
    echo $path->nodeValue; 
} 

或字符串值直接:

$dom = new DOMDocument; 
$dom->load('file.xml'); 
$xPath = new DOMXPath($dom); 
echo $xPath->evaluate('string(/files/file/@path)'); 

您可以获取个人节点也可以通过手动遍历DOM来运行

$dom = new DOMDocument; 
$dom->preserveWhiteSpace = FALSE; 
$dom->load('file.xml'); 
echo $dom->documentElement->firstChild->getAttribute('path'); 

标记此CW,因为这已被多次(只是与不同的元素),包括我回答,但我懒得找到重复。