php SimpleXML 获取节点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5593554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:55:33  来源:igfitidea点击:

SimpleXML get node value

phpxmlsimplexml

提问by priktop

Say I have this following XML structure:

假设我有以下 XML 结构:

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

I made a variable of the XML and now I want to get the values of child1, so I use SimpleXML:

我创建了一个 XML 变量,现在我想获取 child1 的值,所以我使用 SimpleXML:

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

But I get this message: Notice: Trying to get property of non-object in /x.php on line x

但我收到此消息:注意:尝试在第 x 行的 /x.php 中获取非对象的属性

I also tried it with $xml->parent->child1, but no success.

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

Anyone??

任何人??

回答by vartec

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

回答by Paul

A good example of using XPath with php for the SimpleXMLElement can be found here http://www.php.net/manual/en/class.simplexmlelement.php#95229

可以在此处找到将 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);