I’m using a variable to create an element. But I’m getting this error:
Warning: DOMDocument::createElement() expects parameter 1 to be string, object given
// load up your XML
$xml = new DOMDocument;
$xml->load('test.xml');
$parent_node = $xml->createElement('parent');
foreach ($xml->getElementsByTagName('product') as $product )
{
$append = array();
foreach($product->getElementsByTagName('name') as $name ) {
// Stick $name onto the array
$append[] = $name;
}
foreach ($append as $a) {
$parent_node->appendChild($xml->createElement($a, 'anothervalue'));
$product->appendChild($parent_node);
}
$product->removeChild($xml->getElementsByTagName('details')->item(0));
//$product->appendChild($element);
}
// final result:
$result = $xml->saveXML();
Original XML structure:
<products>
<product>
<name>text</name>
<name>text</name>
<name>text</name>
</product>
</products>
I’m trying to create a new element whose value is the text of itself. I know what it has to look like. Why can’t I use an object to create an element?
The result I’m trying to obtain will look like this:
<products>
<product>
<text>text</text>
<text>text</text>
<text>text</text>
</product>
</products>
You can’t pass an object, you must use the
textContentornodeValueproperties:You may also want to strip it from illegal characters first: