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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the quick reply. Would the system file path (local file name) be "/Users/MyName/.../..."? Or is it something else?
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.
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()?
just create a file containing <?php echo __FILE__; in the same folder as your database.xml file and navigate to it using Safari. You should then see the full path displayed in the browser. Take that path and use it in your script file_put_contents('/path/database.xml', $xml->asXML());
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.