Finding the value of a child in a specific attribute
<data>
<gig id="1">
<date>December 19th</date>
<venue>The Zanzibar</venue>
<area>Liverpool</area>
<telephone>Ticketline.co.uk</telephone>
<price>£6</price>
<time>Time TBA</time开发者_JAVA百科>
</gig>
<gig id="2">
<date>Sat. 16th Jan</date>
<venue>Celtic Connection, Classic Grand</venue>
<area>Glasgow</area>
<telephone>0141 353 8000</telephone>
<price>£17.50</price>
<time>7pm</time>
</gig>
Say if I wanted to view the values of "date" from the gig element which has an attribute of 2 how could I do this using php ?
Basically I want to delete the say id 2 and then create it again or just modify it.
using simpleXML how can I just delete a certain part ?
To find nodes, use XPath.
$data->xpath('//gig[@id="2"]');
It will return an array with all <gig/>
nodes with an attribute id
whose value is 2. Usually, it will contain 0 or 1 element. You can modify those directly. For example:
$data = simplexml_load_string(
'<data>
<gig id="1">
<date>December 19th</date>
<venue>The Zanzibar</venue>
<area>Liverpool</area>
<telephone>Ticketline.co.uk</telephone>
<price>£6</price>
<time>Time TBA</time>
</gig>
<gig id="2">
<date>Sat. 16th Jan</date>
<venue>Celtic Connection, Classic Grand</venue>
<area>Glasgow</area>
<telephone>0141 353 8000</telephone>
<price>£17.50</price>
<time>7pm</time>
</gig>
</data>'
);
$nodes = $data->xpath('//gig[@id="2"]');
if (empty($nodes))
{
// didn't find it
}
$gig = $nodes[0];
$gig->time = '6pm';
die($data->asXML());
Deleting arbitrary nodes is an order of magnitude more complicated, so it's much easier to modify the values rather than deleting/recreating the node.
精彩评论