Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php进行xml解析的帮助_Php_Xml - Fatal编程技术网

使用php进行xml解析的帮助

使用php进行xml解析的帮助,php,xml,Php,Xml,我有以下示例xml: <entity id="1"> <name>computer</name> <type>category</type> <entities> <entity id="2"> <name>mac</name> <type>category</type>

我有以下示例xml:

<entity id="1">
    <name>computer</name>
    <type>category</type>
    <entities>
        <entity id="2">
            <name>mac</name>
            <type>category</type>
        </entity>
        <entity id="3">
            <name>linux</name>
            <type>category</type>
            <entities>
                <entity id="4">
                    <name>ubuntu</name>
                    <type>category</type>
                </entity>
                <entity id="5">
                    <name>redhat</name>
                    <type>category</type>
                    <entities>
                        <entity id="6">
                            <name>server</name>
                            <type>category</type>
                        </entity>
                        <entity id="7">
                            <name>desktop</name>
                            <type>category</type>
                        </entity>
                    </entities>
                </entity>
            </entities>
        </entity>
    </entities>
</entity>

计算机
类别
雨衣
类别
linux
类别
ubuntu
类别
红帽
类别
服务器
类别
桌面
类别
如果我有身份证,比如说5号。是否可以检索以下内容:

  • id为5的实体的名称(redhat)
  • 所有子实体及其id和名称(6:服务器和7:桌面)
  • 所有父实体及其id和名称(1:computer、2:mac和3:linux)
我是解析xml的新手。这是仅通过xpath还是xquery/xpath实现的

如果有人能给我一些使用simplexml的示例代码,我将不胜感激

谢谢

您可以使用。

xpath('/*[@id=5]')){
变量转储($元素);
echo'Element及其子体:',$Element[0]->asXML(),PHP_EOL;
echo“实体名称:”,$element[0]->Name,PHP_EOL;
}

提供了非常直观的XML处理,但它比完整的类更为有限。

所以使用xpath而不是xquery的simplexml?您可以使用DOM。提到
<?php
$simpleXml = simplexml_load_string($xml); // or load your file, whatever

if (($element = $simpleXml->xpath('//*[@id = 5]'))) {
    var_dump($element);
    echo 'Element and descendants: ', $element[0]->asXML(), PHP_EOL;
    echo 'Name of the entity: ', $element[0]->name, PHP_EOL;
}