如果xml节点不存在则使用simpleXML创建它?

时间:2011-05-30 16:01:26

标签: php xml

如果xml节点不存在,请使用simpleXML创建它?

当我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
                    )

            )

    )

我想查看是否( node <F><f1>f1<f1></F> )

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

如果不存在,我创建此节点

ANYBODY可以提供方法如何使用simpleXML执行此操作?

1 个答案:

答案 0 :(得分:1)

这很容易:

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

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

echo $sxml->asXML();

你得到:

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