简体   繁体   中英

Parsing an XML with Xpath in PHP

Consider the following code :

$dom = new DOMDocument();
$dom->loadXML($file);

$xmlPath = new DOMXPath($dom);
$arrNodes = $xmlPath->query('*/item');
foreach($arrNodes as $item){
//missing code
}

The $file is an xml and each item has a title and a description. How can I display them (title and description)?

$file = "<item>
   <title>test_title</title>
   <desc>test</desc>
</item>";

I suggest using php's simplexml , with that, you still get xpath functionality, but with easier approach, for example you would access attributes like this:

$name = $item['name'];

Here's an example:

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <items>
        <item title="Hello World" description="Hellowing the world.." />
        <item title="Hello People" description="greeting people.." />
    </items>
</xml>

do.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
    echo $item['title'], ': ', $item['description'], "\n";
}

If your item looks like this:

<item>
    <title>foo</title>
    <description>frob</description>    
</item>

You could use getElementsByTagName() and nodeValue :

foreach($arrNodes as $item){
    print $item->getElementsByTagName('title')->item(0)->nodeValue;
}

Are title and description attributes? E. g. does an item look like this:

<item title="foo" description="frob" />

If so, you could just use getAttribute() :

...
foreach($arrNodes as $item){
    print $item->getAttribute('title');
}

The right XPath expression should be:

/*/item/title | /*/item/desc

Or

/*/item/*[self::title or self::desc]

This is evaluate to a node set with title and desc element in document order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM