29

Any ideas on how I can get PHPs SimplXMLElement to kick off with the following?

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">

The main root will then be:

<Document></Document>

Or do I use simplexml_load_string() to set it up?

Context: I am extending simpleXmlElement to create some kml files.

EDIT

Actually, setting the kml xmlns was laughably easy to do:

new simpleXMLElement('<kml xmlns="http://earth.google.com/kml/2.2">
<Document></Document></kml>');

Just how to set encoding="UTF-8" that is bothering me, seemingly the kml is acceptable without that, but I'd still like to understand how to do it if pos.

Cups
  • 6,901
  • 3
  • 26
  • 30

1 Answers1

57
new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>'
                          .'<kml xmlns="http://earth.google.com/kml/2.2">'
                          .'<Document></Document></kml>');
OZ_
  • 12,492
  • 7
  • 50
  • 68
  • 1
    Blimey, how simple. I think I was sloooowly getting there myself. So the way to think of it is that if you do not implicitly pass an string in the constructor, it'll just squirt in for you. Cheers Oz, nice one. I was under the mistaken belief that I had to somehow mess about with attributes. – Cups May 13 '11 at 17:37
  • 1
    This may have been obvious, but the resulting `$root = new SimpleXML...` element doesn't automatically point to `Document`, so `$root->addChild(...)` would add stuff next to it -- see example http://sandbox.onlinephpfunctions.com/code/d33041ddf62087a5f4d7c67eb8c4983d4ef64116 – drzaus Mar 04 '15 at 07:34
  • To explain a little more about @drzaus comment, it doesn't point to `Document` because the root element in the string xml is the element `kml` of which `Document` is a child of. – PhoneixS Mar 09 '16 at 11:41
  • 2
    Just adding "encoding="UTF-8" doesn't make the resulting XML UTF-8, answer incorrect or title unclear. – Zulgrib Nov 01 '17 at 22:27
  • 1
    The above didn't work for me, but this did: `$xml = new \SimpleXMLElement('');` – Jack Kinsella Feb 04 '20 at 04:27