简体   繁体   中英

PHP: SimpleXML writing issue

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:

权限

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM