2016-07-01 23 views
0

我有位於我的文件系統上的名爲fonts.xml的xml文件。如何有條件地更新文件系統上的xml文件 - PHP

目標:

我想更新屬性<status>其中name是「Aclonica」,但我不知道該怎麼做有條件。

XML:

<fonts> 
    <font> 
    <name>Aclonica</name> 
    <category>Aclonica</category> 
    <variants>100,bold</variants> 
    <status>active</status> 
    </font> 
    <font> 
    <name>Azeebe</name> 
    <category>Sans-serif</category> 
    <variants>100,bold,italic</variants> 
    <status>active</status> 
    </font> 
</fonts> 
+0

可以參考的XML更新此解決方案:http://stackoverflow.com/questions/20540592/replace-specific-node -value-in-xml-using-php –

+0

https://eval.in/598922 – splash58

+0

你是否解決了這個問題? – morels

回答

0

您需要使用DOMDocument類。這樣,您選擇使用數據正常if條件:

解決方案:

$a = $_POST['font']; // here value 'Aclonica' is assigned to $a 
$dom = new DOMDocument(); 

$dom->load('c:/xampp/htdocs/cms/public/fonts/font.xml'); 

foreach ($dom->documentElement->childNodes as $node) { 

    // print_r($node); // >> uncomment for debug purposes 

    if($node->nodeType == 1) { 
     $name = $node->getElementsByTagName('name')->Item(0); 

     if($name->nodeValue == $a) { // >> IMPORTANT: here is the condition you need 

     $OldJobId = $node->getElementsByTagName('status')->Item(0); 

     if($OldJobId->nodeValue == 'active') { 

      $newelement = $dom->createElement('status','inactive'); 

      $OldJobId->parentNode->replaceChild($newelement, $OldJobId); 
     }else{ 

      $newelement = $dom->createElement('status','active'); 
      $OldJobId->parentNode->replaceChild($newelement, $OldJobId); 
     } 
     } 
    } 
} 

$dom->save("c:/xampp/htdocs/cms/public/fonts/font.xml");