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
https://forums.phpfreaks.com/topic/214197-xml-parsing-help/
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
https://forums.phpfreaks.com/topic/214197-xml-parsing-help/#findComment-1114523
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
https://forums.phpfreaks.com/topic/214197-xml-parsing-help/#findComment-1114620
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.