Change XML node element value in PHP and save file

后端 未结 1 570
抹茶落季
抹茶落季 2020-12-05 21:57

    
        John
        test@test.com
        <         


        
相关标签:
1条回答
  • 2020-12-05 22:10

    You can use XPath to find the specific element. SimpleXMLElement->xpath() returns an array of (matching) SimpleXMLElement objects, i.e. you can access and change the data of each element just like you would in "your" foreach loop.

    <?php
    // $testimonials = simplexml_load_file('test.xml');
    $testimonials = new SimpleXMLElement('<testimonials>
        <testimonial id="4c050652f0c3e">
            <nimi>John</nimi>
            <email>test@test.com</email>
            <text>Some text</text>
            <active>1</active>
            </testimonial>
        <testimonial id="4c05085e1cd4f">
            <name>ats</name>
            <email>some@test.ee</email>
            <text>Great site!</text>
            <active>0</active>
        </testimonial>
    </testimonials>');
    
    // there can be only one item with a specific id, but foreach doesn't hurt here
    foreach( $testimonials->xpath("testimonial[@id='4c05085e1cd4f']") as $t ) {
      $t->name = 'LALALA';
    }
    
    echo $testimonials->asXML();
    // $testimonials->asXML('test.xml');
    

    prints

    <?xml version="1.0"?>
    <testimonials>
        <testimonial id="4c050652f0c3e">
            <nimi>John</nimi>
            <email>test@test.com</email>
            <text>Some text</text>
            <active>1</active>
            </testimonial>
        <testimonial id="4c05085e1cd4f">
            <name>LALALA</name>
            <email>some@test.ee</email>
            <text>Great site!</text>
            <active>0</active>
        </testimonial>
    </testimonials>
    
    0 讨论(0)
提交回复
热议问题