0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As I read PHP documentation, addChild takes name and (optional) value, not a SimpleXMLElement as a parameter!
You cannot add a SimpleXML node with addChild. Your node will be castet (and added) to string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.