Link to home
Start Free TrialLog in
Avatar of pillmill
pillmill

asked on

add empty xml node?

If I add an extra node that has no data, I get a
compiler error: Warning: SimpleXMLElement::addChild() [simplexmlelement.addchild]: Element name is required in

How do I fix this?
$xml= simplexml_load_string( "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget</body></note>");


$newElement = simplexml_load_string('<address></address>');


$xml->addChild($newElement);

Open in new window

Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

Try

<?php
$xml= simplexml_load_string( "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget</body></note>");


$xml->addChild('address');
I thought we had answered this recently...
<?php // RAY_temp_pillmill.php

$obj = simplexml_load_string('<tree></tree>');
$obj->addChild("fred");
$obj->fred = 'Flintstone';

echo htmlentities( $obj->asXml() );

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Ray "I thought we had answered this recently..."

It seems like XML and strtotime are the "flavours of the month" at present. Chances are you answered one very similar to it.
Avatar of pillmill
pillmill

ASKER

Thanks. That solved the problem.

Now, instead of one node, I want to "append" a whole xml string to
the original structure. addChild throws an error: "Element name is required".

Is there a way to append with simpleXML?
Do you mean that you just want to tack on another chunk of XML after the last element like so

(before)
</lastElement>
?>

(after)
</lastElement>
<newStuff>...........
?>

I would do this by converting the current XML to a string, doing the append and then creating a new XML. It is not liable to be successful as you will probably break the well-formedness rules for XML

$temp = $xml->asXml();
$temp .= $moreXml;
$newXml = simplexml_load_string( $temp );

Personally I would just create a new child node and put it in there

$xml->addChild("moreXml", $moreXml );


Thanks. Also worked. But some of the entities are with
html characters and some not. How do I change all of the
> and < and still keeps this as an xml object?
Your best option is to encode it as CDATA so that XML does not interpret it. See

http://www.w3schools.com/xml/xml_cdata.asp

You could also try encoding it with htmlentities before inserting in the XML, but CDATA is the "official" way

http://www.php.net/htmlentities
http://www.php.net/html_entity_decode