Curtis Boylan Curtis Boylan - 1 year ago 72
PHP Question

Adding to XML file using PHP with SimpleXML error

I am using a simple simplexml php file to add to my XML file. For some reason it is not placing the record into the XML file and my logs are showing

PHP Fatal error: Call to a member function addChild()

Wondering can someone help me out? Might be something really simple. I am attaching the PHP code and the XML file.


$file = 'news.xml';

$xml = simplexml_load_file($file);

$story = $xml->news->story;

$story->addChild('storyid', '33');
$story->addChild('story_pic', 'images/test.jpg');
$story->addChild('story_title', 'Your Title');
$story->addChild('story', 'This is a test story');
$story->addChild('story_date', '01/01/2001');



<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<story_title>My Test News Story</story_title>
<story_title>My Test News Story2</story_title>

Answer Source

Surely, this has been aswered thousands times but:

$file = './news.xml';

$xml = simplexml_load_file($file);
// `$xml` presents root item (`news`) of your xml tree

// add new `story` to your root item (`news`)
$new_story = $xml->addChild('story');

// add items to newly added `$new_story` element
$new_story->addChild('storyid', '33');
$new_story->addChild('story_pic', 'images/test.jpg');
$new_story->addChild('story_title', 'Your Title');
$new_story->addChild('story', 'This is a test story');
$new_story->addChild('story_date', '01/01/2001');

// save as XML
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download