1

I am using SimpleXML to write to my XML file on my Apache Server. Here is my PHP code:

<?php
  $xmlFile = 'http://localhost/database.xml';
  //$xml = new SimpleXMLElement($xmlFile, NULL, TRUE);
  $xml = simplexml_load_file($xmlFile);
  $xml->addChild("User", "TestUser2");
  file_put_contents($xmlFile, $xml->asXML());
?>

My XML file code:

<Usernames>
  <User>TestUser1</User>
</Usernames>

The problem I am having is that SimpleXML WILL NOT write to my XML file. I have tried many different methods ($xml->asXML($xmlFile), DOMDocument ... ->save) and none of them are working. I changed the permissions on my file and STILL I cannot write to it:

Permissions

I have spent hours today trying to get this to work with no success. If anyone has any type of solution it would be great to hear.

dda
  • 6,030
  • 2
  • 25
  • 34
RMK-Jacob
  • 209
  • 1
  • 4
  • 15

1 Answers1

3

When you write the contents to the file, you should pass a system filepath as the first variable, your $xmlFile variable is a URL. Change this to the local file name and it should save.

Based on your comments, the following should work

<?php
  $xmlFile = 'http://localhost/database.xml';
  $xml = simplexml_load_file($xmlFile);
  $xml->addChild("User", "TestUser2");
  file_put_contents('/Applications/MAMP/htdocs/DataBase/database.xml', $xml->asXML());

But, I would double check the $xmlFile URL - from what you have said, your local URL could be http://localhost/DataBase/database.xml - you should check that you can open your XML file in Safari using the $xmlFile URL.

PassKit
  • 12,231
  • 5
  • 57
  • 75
  • Thanks for the quick reply. Would the system file path (local file name) be "/Users/MyName/.../..."? Or is it something else? – RMK-Jacob Jan 06 '13 at 06:56
  • `echo __FILE__;` will give you the absolute path to current file. Note `__FILE__` is a PHP constant so don't try to replace this with your filename. – PassKit Jan 06 '13 at 07:24
  • Ok. But how does it know what file it should be getting the path to? Do I put `echo __FILE__` after I use `simplexml_load_file()`? – RMK-Jacob Jan 06 '13 at 16:36
  • 1
    just create a file containing `asXML());` – PassKit Jan 06 '13 at 16:41
  • ok Thanks! When I did that I got this: `/Applications/MAMP/htdocs/DataBase/phpfile.php`. So in my PHP file I should change the path of the XML file to be the above, but with database.xml substituted for phpfile.php? – RMK-Jacob Jan 06 '13 at 17:18
  • I just changed my code, and it works!! Thank you so much for helping me! – RMK-Jacob Jan 06 '13 at 17:33