2010-01-20 74 views
2
<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做到这一点?寻找一个特定属性的儿童的价值

基本上我想删除say id 2然后重新创建它或者只是修改它。

使用simpleXML我该如何删除某个部分?

回答

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()); 

删除任意节点的数量级要复杂得多,所以修改值而不是删除/重新创建节点要容易得多。

+0

我不断收到这个错误致命错误:调用第45行的/var/www/sm16832/public_html/cms/index.php中非对象的成员函数xpath() – 2010-01-20 10:48:29

+0

在本例中,$ data是你的SimpleXMLElement对象。为了避免混淆,*总是*在您所代表的节点之后命名您的PHP变量。如果根节点是'',那么你的PHP变量应该是'$ data'。 – 2010-01-20 11:19:48