Jump to content

DOM XML Issue


xclntdesign

Recommended Posts

I've been working on a script to open an XML file, insert a node, then save the file again.

 

$url = '../v3flashslideshow/slideshow_data0.xml';
$xml = new DomDocument();
$xml->formatOutput = true;
$xml->preserveWhitespace = false;
$xml->load($url);
$xpath = new DOMXPath($xml);

$first = $xpath->query('//galleries/gallery/img')->item(0);

// create node
$new = $xml->createElement("img");
$xml->appendChild($new);
$image = $xml->createAttribute("src");
$new->appendChild($image);
$new->setAttribute("src", $_GET['image']);

$first->parentNode->insertBefore($new, $first);

echo $xml->save($url);

 

The above code works except for the fact that it adds the new node twice.

 

When I change the last line to:

 

echo $xml->saveXML(); 

 

to display the code on the screen, it works fine, with the new node added only once.

 

I've tried many different work arounds, and nothing seems to work.

 

Anyone have any ideas?

 

Thanks in advance.

Link to comment
Share on other sites

hmm strange...

 

i personally add the node to the dom after creating and populating it.

 

try this and let us know what happens...

 

$new = $xml->createElement("img");

$image = $xml->createAttribute("src");

$new->appendChild($image);

$new->setAttribute("src", $_GET['image']);

$xml->appendChild($new);

 

Link to comment
Share on other sites

I may be misreading but one more littel tweak

 

$new = $xml->createElement("img");

$image = $xml->createAttribute("src");

$new->appendChild($image);

$new->setAttribute("src", $_GET['image']);

$xml->appendChild($new);

 

you create the src attribute on the $image object but set it on the $new(node) object...

 

should it not be

 

$new = $xml->createElement("img");

$image = $xml->createAttribute("src");

$image->setAttribute("src", $_GET['image']);

$new->appendChild($image);

$xml->appendChild($new);

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.