简体   繁体   中英

Help! How to add Child to specify Node using PHP simpleXML?

my xml structure is:

<users>
    <user id="126">
        <name>老黄牛三</name>
        <watchHistory>
             <whMonthRecords month="2010-10">
                    <whDateList month="2010-10">
                        <date>01</date>
                        <date>02</date>
                        <date>05</date>
                        <date>08</date>
                        <date>21</date>
                    </whDateList>
                    <whDateRecords date="2010-10-01">
                        <item itemID="1">飞越疯人院.老黄牛三.2010-10-01</item>
                        <item itemID="4">回到未.老黄牛三.2010-10-01来</item>
                        <item itemID="5">天天看的哦啊你.2010-10-01来</item>
                    </whDateRecords>
                    <whDateRecords date="2010-10-05">
                        <item itemID="1">飞越疯人院.老黄牛三.2010-10-05</item>
                        <item itemID="4">回到未来.老黄牛三.2010-10-05</item>
                    </whDateRecords>
                </whMonthRecords>
            <whMonthRecords month="2010-11">
             ........
            </whMonthRecords>
       <watchHistory>
    </user>
</users>

now, how can I add child :

<whDateRecords date="2010-10-06">
                    <item itemID="45">飞越疯人院.老黄牛三.2010-10-05</item>
                    <item itemID="432">回到未来.老黄牛三.2010-10-05</item>
                </whDateRecords>

to the node: <whMonthRecords month="2010-10">

Thank you very much!

First, look for the parent of the node you want to add, say you want to add it to the node with month 2010-10, use this xpath:

$xpath = '//whMonthRecords[@month="2010-10"]';
$nodes = $sxml->xpath($xpath); //sxml is the xml object!
$parent = $nodes[0];

Now that you have the parent, you can add the node using addChild method.

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