2011-04-08 149 views
7

说我有这个下面的XML结构:的SimpleXML获取节点值

<?xml version="1.0" encoding="UTF-8"?> 
<main> 
    <parent> 
     <child1>some value</child1> 
     <child2>another value</child2> 
    </parent> 
</main> 

我做了XML的一个变量,现在我想child1的价值,所以我使用的SimpleXML:

$xml = new SimpleXMLElement($xml); 
$this->xmlcode = (string) $xml->main->parent->child1; 

但是我收到这条消息:注意:试图在/x.php上获取非对象的属性x

我也试过用$ xml-> parent-> child1,但没有成功。

任何??

+7

发现*叹*这必须是最常见的错误有史以来之一。将XML文档加载到SimpleXmlElement中时,根节点是SimpleXmlElement,例如, '$ xml =

'。 – Gordon 2011-04-08 10:35:27

+1

感谢Gordon的解释。 – priktop 2011-04-08 10:37:29

回答

22
$xml = new SimpleXMLElement($xml); 
$this->xmlcode = (string) $xml->parent[0]->child1; 
+0

谢谢,明白了:) – priktop 2011-04-08 10:35:47

+1

问题通过添加类型(字符串)(float)来解决。 – JelleP 2015-07-21 06:38:37

2

使用XPath与PHP的SimpleXMLElement对象的一个​​很好的例子可以在这里 http://www.php.net/manual/en/class.simplexmlelement.php#95229

// Find the topmost element of the domDocument 
$xpath = new DOMXPath($xml); 
$child1 = $xpath->evaluate('/main/parent/child1')->item(0); 
+3

SimpleXml可以执行XPath查询。没有必要转换到DOM来这样做。使用评估的唯一好处是在获得输入结果时,您的示例显然不适用。 – Gordon 2011-04-08 10:34:10