Emulating the SimpleXML addChild function available in 5.1.3

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
zirconx
Forum Newbie
Posts: 6
Joined: Sun Jan 21, 2007 9:53 pm

Emulating the SimpleXML addChild function available in 5.1.3

Post by zirconx »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I am writing an app that deals with XML.  I need to use the addChild function to add some elements to a SimpleXML object.  The addChild function only became available in 5.1.3, I'd like my app to work on any 5.x version.  I've read it can be emulated by converting to DOM, using those methods, then converting back.  So I've got something like this:

Code: Select all

if (method_exists($vsf->config->categories,'addChild')) {
	$vsf->config->categories->addChild("category",$cat);
	}
else {
	//dieWithError("Need PHP 5.1.3 or newer");
	addCategory($cat);
	}
But I'm having a heck of a time with these DOM methods... any pointers appreciated.

Code: Select all

function addCategory($newcat) {
	global $vsf;
	// first, convert the SimpleXML object to DOM
	$dom = new DOMDocument;
	$domsxe = dom_import_simplexml($vsf->config);
	$domsxe = $dom->importNode($domsxe,true);
	$domsxe = $dom->appendChild($domsxe);
	
	$tmpcat = $dom->createElement("category");
	
	$dom->categories->appendChild($tmpcat);
	// then convert back to simpleXML
	$vsf->config = simplexml_import_dom($dom);
	
	}

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

[quote="[url=http://forums.devnetwork.net/viewtopic.php?t=30037]Forum Rules[/url] Section 1.1"][b]1.[/b] Select the correct board for your query. Take some time to read the guidelines in the sticky topic.[/quote]
Post Reply