2

This may be a simple question though can´t figure out how to do it. I want to load and modify an xml file, then save the xml through php.

Here is the code:

 $.ajax({
  type: "GET",
  url: "menu.xml",
  dataType: "xml",
  success: function(xml) {
   $(xml).find('menu_item').each(function(){
    //change the value of menu_item
    $(this).empty();
    $(this).text($("textarea").attr("value"));
    //send xml to php
    $.post('save_xml.php', $(xml), function(data){alert("Data Loaded: " + data);});
   }

  }
 });

Here is how save_xml.php looks like:

<?php

    $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
    $file = fopen("file.xml","w");
    fwrite($file, $xml);
    fclose($file);
    echo "ok";

?> 
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
iulian
  • 23
  • 1
  • 1
  • 4

1 Answers1

2

Is this what you are looking for?

$(this) is each of the menu_items you iterate over with .each()

Your code becomes

$(xml).find('menu_item').each(function(){
   $(this).text("New Value");
});

Hope this helps

EDIT

To post this back to the server I would do this:

$.post('save_xml.php', { xml: $(xml)}, function(data){alert("Data Loaded: " + data);});

and then in the PHP file

<?php
  $xml = $_POST['xml'];
  $file = fopen("file.xml","w");
  fwrite($file, $xml);
  fclose($file);
  echo "ok";
?> 

This code is untested, and there could be any number of reasons it doesn't work, write permissions on the files etc.

Jan Petzold
  • 1,561
  • 1
  • 15
  • 24
Alan Whitelaw
  • 16,171
  • 9
  • 34
  • 51
  • thanks, you were helpful! Now how do i send this xml to a php with jquery? i have a save_xml.php that writes the xml on the server. – iulian Jan 12 '11 at 11:40
  • @iulian Glad I could help. Please feel free to accept my answer. To pass the XML back to PHP you need `jQuery.post()` api.jquery.com/jQuery.post Where `data` is the XML you want to write. – Alan Whitelaw Jan 12 '11 at 12:51
  • I think so, for clarity, edit your question with the second part and I will modify my answer. That way you can insert your code clearly. – Alan Whitelaw Jan 12 '11 at 13:05
  • Thanks, I put the modifications. I hope that you can help me. – iulian Jan 12 '11 at 13:24
  • @iulian I have modified the data element that you were posting back to the php file – Alan Whitelaw Jan 12 '11 at 15:50
  • Does this solution actually work? I'm doing something very similar but the new value I specify does not get preserved in the original XML object so the new value is not included in the POST. – Randyaa Jul 05 '12 at 18:28