php 使用 simpleXML 编辑 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2092172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:59:00  来源:igfitidea点击:

edit XML with simpleXML

phpxmlsimplexml

提问by Oliver Bayes-Shelton

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

如何使用 simpleXML 编辑 xml 文件中的值?

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

我知道如何创建文件,但不知道如何编辑现有文件中的值?

回答by cletus

Sure you can edit with SimpleXML:

当然您可以使用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.

查看示例

回答by Jan Han?i?

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

使用 SimpleXML 加载您的 XML 并进行更改。然后您可以使用asXML方法将 XML 保存到文件中(您将文件名作为参数传递):

$xml = new SimpleXMLElement( $xmlString );
// do the manipulation here
$xml->asXML ( '/path/to/your/file.xml' );

回答by ctrygstad

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.

请记住,虽然您可以使用 SimpleXML 编辑 XML,但仍有一些限制。例如,您可以移除或删除节点或元素。您可以清除它使其空白,但不能完全消除它。为此,您需要 DOM 或类似的东西。

回答by CSepulveda

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 文本即可。

test.xml:

测试.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:

和 PHP 代码:

$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:

结果 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!

希望能帮助到你!