简体   繁体   中英

If xml node if not exist create it using simpleXML?

If xml node if not exist create it using simpleXML?

This output when I print_r() my xml

Array
 (
[0] => SimpleXMLElement Object
    (
        [A] => SimpleXMLElement Object
            (
                [a] => a
            )

        [B] => SimpleXMLElement Object
            (
                [b] => b
            )

        [C] => SimpleXMLElement Object
            (
                [c] => SimpleXMLElement Object
                    (
                        [c1] => c1
                    )

            )

        [D] => SimpleXMLElement Object
            (
                [d] => d
            )

        [E] => SimpleXMLElement Object
            (
                [e] => SimpleXMLElement Object
                    (
                        [e1] => e1
                    )

            )

    )
 [1] => SimpleXMLElement Object
    (
        [A] => SimpleXMLElement Object
            (
                [a] => a11
            )

        [B] => SimpleXMLElement Object
            (
                [b] => b11
            )

        [C] => SimpleXMLElement Object
            (
                [c] => SimpleXMLElement Object
                    (
                        [c1] => c11
                    )

            )

        [D] => SimpleXMLElement Object
            (
                [d] => d1
            )

        [E] => SimpleXMLElement Object
            (
                [e] => SimpleXMLElement Object
                    (
                        [e1] => e11
                    )

            )

    )

)

I want to check if ( node <F><f1>f1<f1></F> )

[F] => SimpleXMLElement Object(
          [f1] => f1
 )

if not exist I create this node

ANYBODY could give the ways How can I do this with simpleXML?

That's easy enough:

$xml = '<xml></xml>';
$sxml = new SimpleXMLElement($xml);

if (!isset($sxml->F->f1)) {
   $sxml->addChild('F')->addChild('f1', 'f1');
}

echo $sxml->asXML();

You get:

<?xml version="1.0"?>
<xml><F><f1>f1</f1></F></xml>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM