Jump to content

Add an new xml attribute


paddy_fields

Recommended Posts

Hi, I've tried my best to get my head around this but I'm still coming up short

 

I'm trying to get my script to....

  • find the ADVERT tag (which is already in my XML file)
  • Add a new ROOT tag after ADVERT
  • Add the attribute 'LOADTYPE' to ROOT
  • assign the value 'A' to that attribute

The logic of what I've written makes sense in my head but I'm getting a fatal error of undefined method DOMElement::createAttribute()

 

I've tried researching this but I keep find 'simpleXML' references which isn't the method I'm using!

$xmldoc = new DomDocument( '1.0' );
	$xmldoc->preserveWhiteSpace = false;
	$xmldoc->formatOutput = true;

	if( $xml = file_get_contents( '../xml/totaljobs.xml') ) {
	    $xmldoc->loadXML( $xml, LIBXML_NOBLANKS );

	    // find the <ADVERT> tag
	    $advert = $xmldoc->getElementsByTagName('ADVERT')->item(0);

	    // create the <ROOT> tag
	    $root = $xmldoc->createElement('ROOT');

	    // add the new <ROOT> tag
	    $advert->appendChild($root);

	    // add 'LOADTYPE' attribute to <ROOT>
	    $attr1 = $root->createAttribute('LOADTYPE');

            // Set the value for the LOADTYPE attribute
	   $attr1->value = 'A';

           // Append attribute to 
	   $root->appendChild($attr1);

	   // Save the updated xml
	   $xmldoc->save('../xml/totaljobs.xml');

Is createAttribute() the right way of doing this?

 

I'm completely new at XML so this is quite a learning curve.

Link to comment
https://forums.phpfreaks.com/topic/287591-add-an-new-xml-attribute/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.