按特定属性在PHP中解析XML

时间:2011-10-20 04:33:50

标签: php xml xml-parsing

我需要将<name><URL>标记的值设为subtype="mytype"。如何在PHP中执行此操作? 我在结果中需要文档名称和test.pdf路径。

<?xml version="1.0" encoding="UTF-8"?>
    <test>
        <required>
            <item type="binary">
                <name>The name</name>
            <url visibility="restricted">c:/temp/test/widget.exe</url>
            </item>
            <item type="document" subtype="mytype">
                <name>document name</name>
            <url visiblity="visible">c:/temp/test.pdf</url>
            </item>
        </required>
    </test>

3 个答案:

答案 0 :(得分:3)

使用SimpleXML and XPath,例如

$xml = simplexml_load_file('path/to/file.xml');

$items = $xml->xpath('//item[@subtype="mytype"]');
foreach ($items as $item) {
    $name = (string) $item->name;
    $url = (string) $item->url;
}

答案 1 :(得分:2)

PHP 5.1.2+默认启用了一个名为SimpleXML的扩展程序。它对于解析格式良好的XML非常有用,就像上面的例子一样。

首先,创建一个SimpleXMLElement实例,将XML传递给它的构造函数。 SimpleXML将为您解析XML。 (这就是我觉得SimpleXML的优雅所在 - SimpleXMLElement是整个图书馆的唯一类。)

$xml = new SimpleXMLElement($yourXml);

现在,您可以轻松遍历XML,就好像它是任何PHP对象一样。属性可作为数组值访问。由于您正在寻找具有特定属性值的标记,因此我们可以编写一个简单的循环来遍历XML:

<?php
$yourXml = <<<END
<?xml version="1.0" encoding="UTF-8"?>
    <test>
        <required>
            <item type="binary">
                <name>The name</name>
            <url visibility="restricted">c:/temp/test/widget.exe</url>
            </item>
            <item type="document" subtype="mytype">
                <name>document name</name>
            <url visiblity="visible">c:/temp/test.pdf</url>
            </item>
        </required>
    </test>
END;

// Create the SimpleXMLElement
$xml = new SimpleXMLElement($yourXml);

// Store an array of results, matching names to URLs.
$results = array();

// Loop through all of the tests
foreach ($xml->required[0]->item as $item) {
    if ( ! isset($item['subtype']) || $item['subtype'] != 'mytype') {
        // Skip this one.
        continue;
    }

    // Cast, because all of the stuff in the SimpleXMLElement is a SimpleXMLElement.
    $results[(string)$item->name] = (string)$item->url;
}

print_r($results);

codepad中测试正确。

希望这有帮助!

答案 2 :(得分:0)

您可以使用XML Parser或SimpleXML。

相关问题