How do I parse XML containing custom namespaces using SimpleXML? [duplicate]

I'm wondering how to parse values in XML that appear to have : in their name. I've been using:

$response   = file_get_contents($url);
$data = simplexml_load_string($response);

then doing a:

foreach($data->item as $key => $current){

However, one of the latest feeds that I've been given has colons in the name of the feed as seen in the example below:

<item>
  <title>foo</title>
  <description>foo</description>           
  <ccc:fid>10</ccc:fid>
  <ccc:bid>6</ccc:bid>
 </item>

When i try to create a $current->ccc:bid php does not get to happy (rightfully so). Is there any way to get around this?


Solution 1:

The elements with colons are using namespace prefixes, and it is perfectly valid XML. When using multiple schemas together, namespaces help differentiate elements which have the same name. The way SimpleXMLElement objects in PHP handle it, you can essentially ignore the part before the colon:

$current->fid;

If you do want to find out the namespace portion of the element name, you can do:

$current->fid->getNamespaces();

Solution 2:

the usage of ccc:fid is an extension of the namespace which needs to be declared in xml in order to be able to use it in libraries like simplexml.

Here are some examples of descriptions of usin a namespace:

  • http://www.w3.org/TR/1999/REC-xml-names-19990114/
  • http://www.w3.org/TR/xml-names/

Hope that helps, albeit it is a little complicated.

Solution 3:

The "ccc" is a namespace - you should be able to do

$current->fid