2010-01-20 72 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