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.

1 Answer 1

57
new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>'
                          .'<kml xmlns="http://earth.google.com/kml/2.2">'
                          .'<Document></Document></kml>');
5
  • 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 <?xml> string in the constructor, it'll just squirt <?xml version="1.0"> 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, 2011 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 sandbox.onlinephpfunctions.com/code/…
    – drzaus
    Mar 4, 2015 at 7: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 9, 2016 at 11:41
  • 2
    Just adding "encoding="UTF-8" doesn't make the resulting XML UTF-8, answer incorrect or title unclear.
    – Zulgrib
    Nov 1, 2017 at 22:27
  • 1
    The above didn't work for me, but this did: $xml = new \SimpleXMLElement('<xml version="1.0" encoding="UTF-8"/>'); Feb 4, 2020 at 4:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.