Jump to content

XML Parsing Help


gaza165

Recommended Posts

Hello, I have an xml file below with multiple namespaces called "date".

 

I want to know how to echo out each date that is associated with that "item" if that makes sense.

 

Thanks

 

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>

  <item>
    <title>My Title</title>
    <dc:date>2009-02-12</dc:date>
    <dc:date>2010-09-01</dc:date>
  </item>

</channel>
</rss>

Link to comment
Share on other sites

I had the exact same problem last week:

 

<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>

  <item>
    <title>My Title</title>
    <dc:date>2009-02-12</dc:date>
    <dc:date>2010-09-01</dc:date>
  </item>

</channel>
</rss>';

$xml = new SimpleXMLElement($xml);
$array = $xml->rss->children('http://purl.org/dc/elements/1.1/');
print_r( $array );

Link to comment
Share on other sites

$str = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>

  <item>
    <title>My Title</title>
    <dc:date>2009-02-12</dc:date>
    <dc:date>2010-09-01</dc:date>
  </item>

</channel>
</rss>
XML;
$doc = new DOMDocument();
$doc->loadXML($str);
$xml = new DOMXPath($doc);
// Register the php: namespace (required)
$xml->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (byName only)
$xml->registerPHPFunctions("byName");

function byName($nodes, $name) {
    $temp = explode(':', $nodes[0]->tagName, 2);
    return isset($temp[1])?($temp[1] === $name)$temp[0] === $name);
}

$dates = $xml->query('//item/*[php:function("byName", ., "date")]');/* @var $dates DOMNodeList */
for($i=0,$max = $dates->length; $i<$max; ++$i){
    var_dump($dates->item($i)->nodeValue);
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.