Sure you can. Eg.
Copy<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
Output
Copy<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
Have fun.
Answer from DreamWerx on Stack OverflowPHP
php.net โบ manual โบ en โบ simplexmlelement.construct.php
PHP: SimpleXMLElement::__construct - Manual
See this example: <?php // This XML contains two elements called <child> // One is in the namespace http://example.com, with local prefix 'ws' // The other has no namespace (no prefix, and no default namespace declared) $xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>'; $sx0 = new SimpleXMLElement($xml, 0, false); $sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com'); $sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true); echo " Without: {$sx0->child} By namespace: {$sx1->child} By prefix: {$sx2->child} "; ?> Output: Without: Not in namespace By namespace: In example namespace By prefix: In example namespace
Top answer 1 of 3
152
Sure you can. Eg.
Copy<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
Output
Copy<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
Have fun.
2 of 3
22
In PHP5, you should use the Document Object Model class instead. Example:
Copy$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
Videos
BCCNsoft
doc.bccnsoft.com โบ docs โบ php-docs-7-en โบ simplexmlelement.construct.html
Creates a new SimpleXMLElement object
<?php $sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE); echo $sxe->asXML(); ?>
W3Schools
w3schools.com โบ php โบ php_ref_simplexml.asp
PHP SimpleXML Functions
abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach function global if implements include include_once instanceof insteadof interface isset list namespace new or print private protected public require require_once return static switch throw trait try use var while xor yield yield from PHP Libxml
Reddit
reddit.com โบ r/php โบ so it's possible for simplexmlelement to create invalid xml?
r/PHP on Reddit: So it's possible for SimpleXMLElement to create invalid XML?
November 11, 2014 -
So I was working on a way to convert arrays to XML strings using SimpleXML and felt confident that it would not error if attempting to create invalid XML, but apparently I'm wrong:
$xml = "<foo></foo>"; $xml = new \SimpleXMLElement($xml); $xml->addChild(1,"bar"); $xml = $xml->asXML(); $valid = (bool) @simplexml_load_string($xml); var_dump($xml, $valid);
outputs:
string(44) "<?xml version="1.0"?> <foo><1>bar</1></foo> " bool(false)
I'm mainly posting to vent frustration and to let people know that they can't rely on SimpleXML to always create valid XML
Top answer 1 of 4
11
I see your frustration, but what do you expect PHP / SimpleXML to do here? 1 is by spec not a valid start character. There is no way to transform this properly ("_1" ? "a1"?) so your point should be, that addChild (or asXML? dunno) should throw an exception, if the child name is not valid, which I agree on if there would be a flag to set (BC Break calling here). However, you would get an Exception (fairly late tough) if you'd use the OO-API and used $valid = new \SimpleXMLElement($xml); instead of simplexml_load_string(). In the end, I cannot find a guarantee that SimpleXMLElement::asXML would produce valid XML, just well formed - which frankly is splitting hairs, but kind of true: looks well formed to me. ;) See also the discussion over at SO on this topic. To achieve a proper "is valid xml?" you should check XMLReader::isValid or rely on the different methods described in the docs . Edit: Looks like I am a bit off after all: well formed is usually used in the context of "confronting the design goals of XML" ( citing Wikipedia here ) which includes non-numeric starting characters of elements - BUG! :)
2 of 4
2
I just encountered this the other day. What's even greater is if you then load the result into a DOMDocument it will generate an error.
Reintech
reintech.io โบ blog โบ beginners-guide-php-simplexml-library-xml-parsing
A Beginner's Guide to the PHP SimpleXML Library for XML Parsing | Reintech media
April 21, 2023 - function arrayToXml($data, $xml = null, $rootName = 'root') { if ($xml === null) { $xml = new SimpleXMLElement("<$rootName/>"); } foreach ($data as $key => $value) { // Handle attributes if (strpos($key, '@') === 0) { $xml->addAttribute(substr($key, 1), $value); continue; } // Handle text content if ($key === '_text') { $xml->{0} = $value; continue; } // Handle arrays and objects if (is_array($value)) { $child = $xml->addChild($key); arrayToXml($value, $child); } else { $xml->addChild($key, htmlspecialchars($value)); } } return $xml; } $jsonData = json_decode('{"product":{"@id":"123","name":"Laptop","price":"999.99"}}', true); $xml = arrayToXml($jsonData); echo $xml->asXML();
Marcysutton
marcysutton.com โบ simple-xml-in-php
Simplexml in php 5 - MarcySutton.com
<?php $file = file_get_contents('navigation.xml'); $xml = new SimpleXMLElement($file); ?>