简体   繁体   English

PHP的DOM XML获取节点值

[英]php dom xml get node value

I am working on a project, which works with .xml files. 我正在研究一个可处理.xml文件的项目。 I encountered a problem. 我遇到了一个问题。 I use simplexml for reading and changing values of nodes. 我使用simplexml来读取和更改节点的值。 And As I need to add and remove nodes I have to use DOM as well. 而且,由于我需要添加和删除节点,因此我也必须使用DOM。 I read through DOM documentation over on the php.net site and I understand the concept and how it works, but. 我在php.net网站上通读了DOM文档,但我理解了该概念及其工作原理。

I load external .xml file. 我加载了外部.xml文件。 to $xmlpath="./menu.xml"; 到$ xmlpath =“ ./ menu.xml”; the file is way bigger, but important part is: 该文件要大得多,但重要的部分是:

<?xml version="1.0" encoding="utf-8"?>
<menu>
    <den>
        <nazev>pondeli</nazev>
    </den>
</menu>

My php code is: 我的PHP代码是:

$dom=new DOMDocument(); // iniciate DOM
$dom->load($xmlpath); // load xml file
$path = new DOMXPath($dom); // prepare path
echo $path->den[0]->nazev->nodeValue;

I just simply cannot wrap my head around this, why this doesn't work. 我只是无法解决这个问题,为什么这行不通。 I am certain I might be doing something wrong, but I have no idea what it is. 我确定我可能做错了什么,但我不知道这是什么。 I know I can just use simpleXML for doing this, but I wanted to use this, to teach myself use DOM. 我知道我可以使用simpleXML来做到这一点,但是我想使用它来教自己使用DOM。 Thank you all in advance. 谢谢大家。

Using the item functions you can get the element you are looking for 使用item函数,您可以获得所需的元素

$path->item(0)->nodeValue; $ path-> item(0)-> nodeValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM