<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>
如果我想从具有属性2的gig元素查看“date”的值,我该如何使用php执行此操作?
基本上我想删除说id 2,然后再创建它或者只是修改它。
使用simpleXML我怎样才能删除某个部分?
答案 0 :(得分:1)
要查找节点,请使用XPath。
$data->xpath('//gig[@id="2"]');
它将返回一个数组,其中所有<gig/>
个节点的属性为id
,其值为2.通常,它将包含0或1个元素。您可以直接修改它们。例如:
$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());
删除任意节点要复杂一个数量级,因此修改值比删除/重新创建节点要容易得多。