View Full Version : Change XML Attribute with PHP

07-08-2009, 12:19 AM

I'm trying to use PHP to change the value of an XML element attribute but it's not working. I have an XML file laid out like this:

<?xml version="1.0" encoding="utf-8" ?>
<add key="dog" value="cat"/>
<add key="fish" value="bird"/>

I have a HTML form where a users can change the values of the keys. So they input the "key" they want to change, and the new "value" for that key.

I'm sending the values from the form to the PHP file through JavaScript with this JS code:

function modifyXML(){
var key = document.getElementById("modifiedKey").value;
var value = document.getElementById("modifiedValue").value;

var getVar = "?key=" + key + "?value=" + value;

var request = GXmlHttp.create();

request.open('GET', 'modifyXML.php' + getVar, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {

That part is working. I know that the values are making it into the getVar variable, so the problem must be after that. The PHP file is as follows:

header('Content-Type: text/xml;charset=UTF-8');

$key = (float)$_GET['key'];
$value = (float)$_GET['value'];

$xdoc = new DOMDocument();
$adds = $xdoc->getElementsByTagName('add');

foreach ($adds as $add) {
if ($add->getAttribute("key") == $key) {
$add->setAttribute("$key", "$value");


I can't figure out why it's not working. The request.readyState of the PHP request never reaches 4 (so the page never reloads).

Anyone have any ideas?

Thanks very much in advance for any help.

07-08-2009, 12:28 AM
Actually, I was just playing around putting an alert at different places in the JavaScript code and I've found out that the JavaScript gets stuck at the line var request = GXmlHttp.create(); (the alert will show up if before that line but not after it). Anyone have any idea why this could be? I have other JavaScripts running on this same server that use that exact same line of code without any problems.

07-08-2009, 03:44 AM
Alright, silly me. var request = GXmlHttp.create(); wasn't working because GXmlHttp is a google maps thing and I hadn't included the google maps JS file.

07-08-2009, 04:06 AM
Still trying to figure out why my PHP file isn't causing any changes in the XML file though....