How to save an XML file on the web server using PH

2019-02-26 02:56发布

问题:

I am a beginner in PHP and I know nothing about XML manipulation. I am working on a Google CSE annotation XML shown below:

  <?xml version="1.0" encoding="UTF-8" ?> 
- <Annotations>
- <Annotation about="http://sanspace.in/">
  <Label name="_cse_byxamvbyjpc" /> 
  </Annotation>
- <Annotation about="http://blog.sanspace.in/">
  <Label name="_cse_byxamvbyjpc" /> 
  </Annotation>
- <Annotation about="http://google.com/">
  <Label name="_cse_exclude_byxamvbyjpc" /> 
  </Annotation>
  </Annotations>

I want achieve this from the above shown file:

  <?xml version="1.0" encoding="UTF-8" ?> 
- <Annotations>
- <Annotation about="http://sanspace.in/">
  <Label name="testString1" /> 
  </Annotation>
- <Annotation about="http://blog.sanspace.in/">
  <Label name="testString2" /> 
  </Annotation>
- <Annotation about="http://google.com/">
  <Label name="testString2" /> 
  </Annotation>
  </Annotations>

So far, I have tried:

<?php
if (file_exists('test.xml'))
  {
  $xml = simplexml_load_file('test.xml');
  }
else
  {
  exit('Error.');
  }
foreach($xml->Annotation as $annotation)
    {
    if ($annotation["about"]=="http://sanspace.in/") 
        {  $annotation->Label["name"]="testString1";  } 
    else 
        {  $annotation->Label["name"]="testString2";  } } 

$dom = new DOMDocument('1.0'); 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
$dom->loadXML($xml->asXML()); 
echo $dom->saveXML();
$dom->save("test.xml");
?> 

This code performs the task but it doesn't save it into the file.

My question is, what's wrong with the $dom->save("test.xml"); statement? How do I save the XML file on the server?

回答1:

I don't see anything wrong with your code. I think you have a permission problem.

PHP is running as one of the following two users:

  • nobody or possibly www-data (aka the system user the web server uses)
  • Your user name

For PHP to run as the user that owns the web root (i.e. you), suexec has to be enabled for PHP. The fact that you can't write to a file with 0644 permissions pretty much says that it is not.

You have two options:

  • Re-configure the server so PHP runs as the user that owns the web root
  • Make the file world write-able

I highly recommend the first over the second. However, you don't always have that choice. If your host (or sysadmin, or whoever) can't or won't enable suexec for PHP, you'll have to give the file 0777 permissions, aka rwxrwxrwx.

You might want to login via ssh and create the output file using the touch command first (or directory, if that's what you need via mkdir), then give it the needed permissions.



回答2:

There is nothing wrong with $dom->save("test.xml");.
You dont need to do the save with DOM though. Could just as well do it with SimpleXML:

$xml->saveXML("test.xml");

Make sure the destination folder is writable. Use an absolute path to make sure you are actually looking for the file in the right location.