edit XML with simpleXML

前端 未结 4 406
醉酒成梦
醉酒成梦 2020-11-30 14:56

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条回答
  • 2020-11-30 15:28

    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!

    0 讨论(0)
  • 2020-11-30 15:40

    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.

    0 讨论(0)
  • 2020-11-30 15:47

    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.

    0 讨论(0)
  • 2020-11-30 15:48

    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' );
    
    0 讨论(0)
提交回复
热议问题