I get this error when running this code: Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in test.php:29 Stack trace: #0 test.php(29): DOMDocument->createElement('1OhmStable', 'a') #1 {main} thrown in test.php on line 29
Nodes that contain invalid characters from the source XML file, but since I am deleting invalid characters from nodes, you must create nodes. What type of coding do I need to do for the original XML document? Do i need to decode saveXML?
function __cleanData($c) { return preg_replace("/[^A-Za-z0-9]/", "",$c); } $xml = new DOMDocument('1.0', 'UTF-8'); $xml->load('test.xml'); $xml->formatOutput = true; $append = array(); foreach ($xml->getElementsByTagName('product') as $product ) { foreach($product->getElementsByTagName('name') as $name ) { $append[] = $name; } foreach ($append as $a) { $nodeName = __cleanData($a->textContent); $element = $xml->createElement(htmlentities($nodeName) , 'a'); } $product->removeChild($xml->getElementsByTagName('details')->item(0)); $product->appendChild($element); } $result = $xml->saveXML(); $file = "data.xml"; file_put_contents($file,$result);
Here's what the original XML looks like:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="/v1/xsl/xml_pretty_printer.xsl" type="text/xsl"?> <products> <product> <modelNumber>M100</modelNumber> <itemId>1553725</itemId> <details> <detail> <name>1 Ohm Stable</name> <value>600 x 1</value> </detail> </details> </product> </products>
The new document should look like this:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="/v1/xsl/xml_pretty_printer.xsl" type="text/xsl"?> <products> <product> <modelNumber>M100</modelNumber> <itemId>1553725</itemId> <1 Ohm Stable> </1 Ohm Stable> </product> </products>
source share