edit XML with simpleXML

2020-01-27 08:19发布

How can I edit the value's in a xml file using simpleXML ?

I know how to create the file, but not how to edit the value in an existing file ?

4条回答
够拽才男人
2楼-- · 2020-01-27 08:47

Load your XML with SimpleXML and make the changes. Then you can use the asXML method to save the XML to a file (you pass the filename as the argument):

$xml = new SimpleXMLElement( $xmlString );
// do the manipulation here
$xml->asXML ( '/path/to/your/file.xml' );
查看更多
Animai°情兽
3楼-- · 2020-01-27 09:05

I am working like this (it's quite the same but it could help): The file test.xml could be any extension as long as it's a plain xml text.

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<sitedata>
    <Texts>
        <ANode SomeAttr="Green" OtherAttr="Small"/>This is the text I'm changing.</ANode>
    </Texts>
</sitedata>

And the PHP code:

$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$SomeVar="<b>Text. This supports html code.</b><br/>I also work with variables, like GET or POST.";
$xml->Texts[0]->{'ANode'}=$SomeVar;
$xml->asXml('test.xml');

Results test.xml:

<?xml version="1.0" encoding="utf-8"?>
<sitedata>
    <Texts>
    <ANode SomeAttr="Green" OtherAttr="Small"/>&lt;b&gt;Text. This supports html code.&lt;/b&gt;&lt;br/&gt;I also work with variables, like GET or POST.</ANode>
    </Texts>
</sitedata>

Hope it helps!

查看更多
萌系小妹纸
4楼-- · 2020-01-27 09:06

Sure you can edit with SimpleXML:

$input = <<<END
<?xml version='1.0' standalone='yes'?>
<documents>
  <document>
    <name>spec.doc</name>
  </document>
</documents>
END;

$xml = new SimpleXMLElement($input);
$xml->document[0]->name = 'spec.pdf';
$output = $xml->asXML();

Take a look at the examples.

查看更多
5楼-- · 2020-01-27 09:06

Keep in mind that although you can edit XML with SimpleXML, there are limitations. For example, you can remove or delete a node or element. You can clear it so that its blank, but you can't eliminate it altogether. For that, you need DOM, or something like that.

查看更多
登录 后发表回答