Reputation: 736
I am trying to output an XML file from PhP using SimpleXML. I have run into problems with the ":" (colon) character. (Talk about art imitating life!)
Is there any way to escape the colon so I can add my elements to the object?
Here is my code:
$urlset->addAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9');
This line passes okay, so it is only the attribute name that is failing, as in the below examples:
$urlset->addAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
$urlset->addAttribute('xsi:schemaLocation','http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
In each case, it lops off anything preceding the ":", like so:
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
>
Again, my problem is not with reading/parsing the ":" from XML, but with writing the ":" to XML from PHP. There is lots on parsing on the 'net, but I've found nothing on writing a ":" from PHP.
Upvotes: 0
Views: 169
Reputation: 36
It appears that you can't use SimpleXML to define the namespaces that are going to be used in the document (which is what the xmlns
attributes do). I've found that you can simply specify them in the declaration of your root node like this:
$simpleXml = new SimpleXMLElement('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"></urlset>');
In your case of building a sitemap, you probably won't have to worry about setting any namespaces beyond that. However, for a more generic solution, this defines a default namespace and a second namespace with the prefix alt
.
$simpleXml = new SimpleXMLElement('<root xmlns="http://default.namespace.com" xmlns:alt="http://alt.namespace.com"></root>');
$simpleXml->addChild("child", "node in the default namespace");
$simpleXml->addChild("other", "node in the alternate namespace", "http://alt.namespace.com");
print $simpleXml->asXML();
will yield:
<root xmlns="http://default.namespace.com" xmlns:alt="http://alt.namespace.com">
<child>node in the default namespace</child>
<alt:other>node in the alternate namespace</alt:other>
</root>
The third optional argument to addAttribute
is the namespace which can help you create attributes or nodes with that name space. Note that you need to use the url of the namespace (not the prefix).
Upvotes: 2