Adding child node in xml file
I have an xml file
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<descript开发者_StackOverflowion>HTML Tags</description>
</event>
</events>
</xml>
How i can add another event inside events tag with respect to date
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<description>HTML Tags</description>
</event>
<event>
<title>Another Title</title>
<description>Another description</description>
</event>
</events>
</xml>
i used this code
$xml_str = file_get_contents($xmlfile);
$xml = new SimpleXMLElement($xml_str);
$event = $xml->events->addChild('event');
$event->addChild('title', 'More Parser Stories');
$event->addChild('description', 'This is all about the people who make it work.');
file_put_contents($xmlfile, $xml->asXML());
But it will add to the first node.How i can add to events tag with date 02-09-2010
You'll have to query for the wanted <events>
tag instead of taking the first one (which what $xml->events
would simply return), using xpath
to query the xml document is helpful here:
PHP Script:
<?php
$xml_str = file_get_contents('xmlfile');
$xml = new SimpleXMLElement($xml_str);
$wantedEventsTag = $xml->xpath('/xml/events[@date="02-09-2010"]');
$wantedEventsTag = $wantedEventsTag [0];//since above fun will return an array
$wantedEventsTag['attrname']='attrval';//Here's how to add an attribute
$event = $wantedEventsTag->addChild('event');
$event->addChild('title', 'More Parser Stories');
$event->addChild('description', 'This is all about the people who make it work.');
file_put_contents('xmlfile.xml', $xml->asXML());
Sample XML File with multiple <events>
tags:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="01-01-1999">
</events>
<events>
</events>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<description>HTML Tags</description>
</event>
<event>
<title>Another Title</title>
<description>Another description</description>
</event>
</events>
</xml>
the script xpath
will match the required node, which we later use and add events subnodes to.
You'll need to use DOM instead, specifically DOMNode::insertBefore:
http://us.php.net/manual/en/domnode.insertbefore.php
精彩评论