dayana
dayana

Reputation: 79

Parse XML in PHP by specific attribute

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>

Upvotes: 1

Views: 1508

Answers (3)

Phil
Phil

Reputation: 164731

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

Upvotes: 3

user74328
user74328

Reputation: 94

You can use the XML Parser or SimpleXML.

Upvotes: 0

Jonathan Chan
Jonathan Chan

Reputation: 2389

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!

Upvotes: 2

Related Questions