how do I properly address accessing tags in XML that are built like this:

<mm:Track>
<dc:title>TRACKNAME</dc:title>
<mm:trackNum>TRACKNUMBER</mm:trackNum>
</mm:Track>

foreach ($xml->channel->item as $item)
{
	$tracknr 	= $item->mm:Track->mm:trackNum;
	$title 		= $item->mm:Track->dc:title;
	$artist 	= $item->mm:Artist->dc:title;
	$album 		= $item->mm:Album->dc:title;	

echo $artist.' - '.$album.' - '.$tracknr.' - '.$title;
}	

...throws an error on the ':'

if it helps, the namespaces are defined as:

xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:mm="http://musicbrainz.org/mm/mm-2.1#"

    It looks like since SimpleXML treats the colon character as a namespace definition, you will need to strip them out prior to processing.

    I can across this link when looking for an answer.

    The page is mainly referring to SOAP responses, but you can use the same logic. Here is the relevant code from that page:

    // SimpleXML seems to have problems with the colon ":" in the <xxx:yyy> response tags, so take them out
    $xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
    
    // Use SimpleXML to parse response into object
    $xml = new SimpleXMLElement($xmlString);
    

    Hope this helps you...

      nice hack!... only requires on extra line (minus yours)...

      original:

      $xml = simplexml_load_file($songFeed);
      

      modified:

      $xml = file_get_contents($songFeed);
      $xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml); 
      $xml = simplexml_load_string($xml);
      

      i dont really understand:

      "$1$2$3"
      

      can anyone explain that?

      also... how do i access attributes by name...

      	<azProductInfo>
      	<azDetails url="some-url" />
      	</azProductInfo>
      

      i've tried:

      $item->azProductInfo->azDetails->attributes('url');
      

      but to no avail

        try this (Untested...)

        $item->azProductInfo->azDetails['url']

          If that doesn't work, you may need to go the long route... (again, untested....)

          $details = $item->azProductInfo[0];
          $url = $details['url'];
          

          or if you are looping through the XML...

          foreach ($item->azProductInfo as $az_product_info) {
              foreach ($az_product_info->azDetails as $az_details) {
                  $url = $az_details['url'];
              }
          }
          

            thanks for the help... i found this to work

            $item->azProductInfo->azDetails->attributes()->url;
            

            thanks again for all the help!

              10 years later
              Write a Reply...