XML DOMDocument PHP - 获取属性值所在的节点 [英] XML DOMDocument PHP - Get node where attribute value

查看:40
本文介绍了XML DOMDocument PHP - 获取属性值所在的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的:

创建一个方法来检索具有特定id"的嵌套元素.

Create a method to retrieve a nested element with a specific "id".

我尝试过的:

  • 通过 DOMXpath 类查询方法检索带有 x 路径表达式的代码.每次返回一个空节点列表
    • '/row[@id=' .$id .']'
    • '//表/行[@id=' .$id .']'
    • '//[@id=' .$id .']'
    • '//[@id=' . $id . ']'

    示例 XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <table>
      <row id="1">
        <job>construction</job>
        <age>34</age>
        <name>bob</name>
      </row>
      <row id="2">
        <job>construction</job>
        <age>34</age>
        <name>bob</name>
      </row>
      <row id="3">
        <job>construction</job>
        <age>34</age>
        <name>bob</name>
      </row>
      <row id="4">
        <job>construction</job>
        <age>34</age>
        <name>bob</name>
      </row>
    </table>
    

    PHP 代码:

    Class SimpleORM{
    
        ...
    
        public function find($id)
        {
            settype($id, "int");
            $xpath = new DOMXPath($this->_dom);
            $expression = '/row[@id=' . $id . ']';
            return $xpath->query($expression);
        }
    
    }
    

    完整的 PHP 代码可以在这里阅读 -> https://github.com/Danoon/SimpleORM/blob/master/SimpleORM.php

    The fUll Php code can be read here -> https://github.com/Danoon/SimpleORM/blob/master/SimpleORM.php

    问题:

    为什么没有返回正确的元素/节点,我该如何实现?

    Why is the proper element/node not returned and how can i achieve this?

    调用查找函数

    $users = new SimpleORM("users");
    $result = $users->find(1);
    

    推荐答案

    试试这个

        <?php
        $slideids = array();
        $get_id = 2; 
        $xml = new DOMDocument();
        $xml->load('test.xml'); // path of your XML file ,make sure path is correct
        $xpd = new DOMXPath($xml);
        false&&$result_data = new DOMElement(); //this is for my IDE to have intellysense
        $result = $xpd->query("//row[@id=".$get_id."]/*");  // change the table naem here
        foreach($result as $result_data){
            $key = $result_data->nodeName;
            $values = $result_data->nodeValue;
            $slideids[$key] = $values;
        }
    
        echo '<pre/>';
        print_r($slideids);
    ?>
    

    XPath 查询/表达式参考手册

    这篇关于XML DOMDocument PHP - 获取属性值所在的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆