Viewed   64 times

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?

 Answers

3

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.

Sunday, November 20, 2022
1

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

Tuesday, November 29, 2022
 
juxhin
 
3

Usually, people use children().

$rss = simplexml_load_string(
    '<?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0" xmlns:moshtix="http://www.moshtix.com.au">
        <channel>
            <link>qweqwe</link>
            <moshtix:genre>asdasd</moshtix:genre>
        </channel>
    </rss>'
);

foreach ($rss->channel as $channel)
{
    echo 'link: ', $channel->link, "n";
    echo 'genre: ', $channel->children('moshtix', true)->genre, "n";
}
Friday, August 12, 2022
 
3

You could work with XPath and registerXPathNamespace():

$xml->registerXPathNamespace("georss", "http://www.georss.org/georss");
$xml->registerXPathNamespace("gml", "http://www.opengis.net/gml");
$pos = $xml->xpath("/georss:where/gml:Point/gml:pos");

From the docs, emphasis mine:

registerXPathNamespace […] Creates a prefix/ns context for the next XPath query.

More ways to handle namespaces in SimpleXML can be found here, for example:
Stuart Herbert On PHP - Using SimpleXML To Parse RSS Feeds

Thursday, October 6, 2022
 
4

Originally posted as a comment, since I haven't verified it, but:

<Prop1>Some Value</Prop1>

is not the same as

<ns0:Prop1>Some Value</ns0:Prop1>

So to get it working, you probably just need:

[XmlElement(Namespace="")]
public string Prop1 { get; set; }

[XmlElement(Namespace="")]
public string Prop2 { get; set; }
Sunday, December 25, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :