在简单的XML文件上使用DOMDocument PHP类

时间:2014-07-07 17:50:41

标签: php xml domdocument

我的XML文档如下。

<?xml version="1.0" encoding="utf-8"?>
<userSettings>
    <tables>
        <table id="supertable">
            <userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
        </table>
        <table id="almost-supertable">
            <userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
        </table>
    </tables>
</userSettings>

我正在使用以下PHP代码加载文件(DOMDocument),然后DomXpath来遍历文档

<?php
...
    $xmldoc = new DOMDocument();
    $xmldoc->load ($filename);

    $xpath = new DomXpath($xmldoc);

    $x = $xpath->query("//tables/table");
    $y = $x->item(0);
...
?>

$y变量现在包含DOMElement对象,其nodeValue属性包含字符串,如下所示:

["nodeValue"]=>
string(81) "
        {"id":"colidgoeshereX"}
        {"id":"colidgoeshereY"}
"

我的问题是,<userTabLayout>节点发生了什么变化?为什么我不将此视为<table>节点的子节点?如果我想访问<userTabLayout id="B">节点,我该怎么做?

通常我会阅读有关此类内容的文档,但官方PHP页面上的官方文档确实很少。

2 个答案:

答案 0 :(得分:0)

嗯,你可以在没有DomXpath的情况下工作。

$xmlS = '
<userSettings>
    <tables>
        <table id="supertable">
            <userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
        </table>
        <table id="almost-supertable">
            <userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
        </table>
    </tables>
</userSettings>
';

$xmldoc = new DOMDocument();
$xmldoc->loadXml($xmlS);

$table1 = $xmldoc->getElementsByTagName("tables")->item(0);
$userTabLayoutA = $table1->getElementsByTagName("userTabLayout")->item(0);
$userTabLayoutB = $table1->getElementsByTagName("userTabLayout")->item(1);

echo $userTabLayoutA->nodeValue; // {"id":"colidgoeshereX"}
echo $userTabLayoutB->nodeValue; // {"id":"colidgoeshereY"}

如您所见,您可以使用getElementsByTagName逐个访问所有元素,并指定您想要的项目。

答案 1 :(得分:0)

  

我的问题是,<userTabLayout>节点发生了什么?

没有发生任何事。 <userTabLayout>元素是$y DOMElement 的子元素。

  

为什么我不将此视为<table>节点的子节点?

因为您没有使用nodeValue字段来查找子节点。

  

如果我想访问<userTabLayout id="B">节点,我该怎么做?

通过遍历文档,例如通过childNodes字段访问子节点(惊喜)。

  

通常我会阅读有关此类内容的文档,但官方PHP页面上的官方文档确实很少。

这是因为已经由W3C记录了DOM,例如在这里:http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/

由于该链接是规范,因此可能有点技术性,因此难以使用,但您可以认为它已完成(例如,如果您需要了解它,请检查是否真实)。一旦理解了DOM的指定,您就可以与任何可用的DOM文档相关联,例如在MDN中,甚至在Javascript(W3C的两个默认实现之一)中,它在PHP中的工作方式类似(特别是对于遍历或Xpath如何工作)

玩得开心!