Parse XML in PHP by specific attribute

夙愿已清 提交于 2019-12-08 07:26:58

问题


I need to get <name> and <URL> tag's value where subtype="mytype".How can do it in PHP? I want document name and test.pdf path in my result.

<?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>

回答1:


Use SimpleXML and XPath, eg

$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;
}



回答2:


PHP 5.1.2+ has an extension called SimpleXML enabled by default. It's very useful for parsing well-formed XML like your example above.

First, create a SimpleXMLElement instance, passing the XML to its constructor. SimpleXML will parse the XML for you. (This is where I feel the elegance of SimpleXML lies - SimpleXMLElement is the entire library's sole class.)

$xml = new SimpleXMLElement($yourXml);

Now, you can easily traverse the XML as if it were any PHP object. Attributes are accessible as array values. Since you're looking for tags with specific attribute values, we can write a simple loop to go through the 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);

Tested to be correct in codepad.

Hope this helps!




回答3:


You can use the XML Parser or SimpleXML.



来源:https://stackoverflow.com/questions/7831194/parse-xml-in-php-by-specific-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!