2017-09-04 79 views
1

我有元素在XML像下面读取属性的XML值包含前缀与元素名称冒号和属性名

<user:name test:one = "firstUser" /> 

我用PHP DOM的XPath读取XML

$ DOC =新的DOMDocument();

$xpath = new DOMXPath($doc); 
$xml = simplexml_load_file(file path here); 
echo '<pre>'; print_r($xml); 

和输出是空白

SimpleXMLElement Object 
(
) 

如果我尝试删除和前缀像下面

<name one = "firstUser" /> 

然后读取元素。输出

SimpleXMLElement Object 
(
    [name] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
     (
      [one] => firstUser 
     ) 
    ) 
) 

如何我可以前缀和冒号(:)

更新的读取元素值:示例XML文件

<?xml version="1.0" encoding="UTF-8"?> 
<root xmlns:test="http://www.w3.org/2001/XMLSchema" xmlns:user="http://www.w3.org/2001/XMLSchema"> 
    <user:name test:one = "firstUser" /> 
    <name second = "secondUser" /> 
</root> 
+0

在http://php.net/manual/en/function.simplexml-load-file.php中添加'user'作为命名空间,也许'test'也是 – Edwin

+0

还是同样的问题 – hrishi

+0

你用什么php版本?检查:https://3v4l.org/ijeHp它的工作原理,但有一些警告 – Edwin

回答

2

使用DOMDocument要经过文件:

<?php 
$doc = new DOMDocument(); 
$doc->load("file.xml"); 
$root = $doc->getElementsByTagName("root"); 
echo "<pre>"; 
foreach ($doc->getElementsByTagName("name") as $users) { 
    echo $users->nodeName.":"; 
    foreach ($users->attributes as $attr) { 
     echo $attr->name." ".$attr->value."<br>"; 
    } 
    echo "<br>"; 
} 

Demo (XML loaded from string)