2016-05-13 24 views
1

請指教。我有XML,我需要通過PHP來糾正。 XML的如何根據預設參數找到並替換XML中的值

例如

<?xml version="1.0"?> 
<csv_data> 
<row> 
    <articul>1107134</articul> 
    <type>car tires</type> 
    <brand>Aeolus</brand> 
    <name>Aeolus AL01 Trans Ace 195/75 R16C 107/105R</name> 
    <season>summer</season> 
</row> 
<row> 
    <articul>1107134</articul> 
    <type>car tires</type> 
    <brand>Aeolus</brand> 
    <name>Aeolus AL01 Trans Ace 195/75 R16 107/105R</name> 
    <season>summer</season> 
</row> 
</csv_data> 

在結果我需要在<type>car tires</type>替換到<type>new car tires</type>,如果有像<name></name> 「R16C」(或R12C,R13C等)的值。符號「C」表示「新車輪胎」類型。否則,請不要更改字段名稱。

我有錯誤 「的foreach()在XML-parser.php提供的無效參數」

該怎麼做,請指教

$filename="./mos-test2.xml"; 
    $dom = simplexml_load_file($filename); 

    foreach ($dom->documentElement->childNodes as $node) { 
    //print_r($node); 
    if($node->nodeType==1){ 
    $OldJobId = $node->getElementsByTagName('name')->Item(0); 
    $newelement = $dom->createElement('name','new car type'.$OldJobId->nodeValue); 
    $OldJobId->parentNode->replaceChild($newelement, $OldJobId); 
    } 
    } 

    $str = $dom->saveXML($dom->documentElement); 
+0

我已經張貼一個答案,但它不包括''對你的問題的符號C'一部分,我會有點更新 –

回答

0
  1. 獲取所有的行節點$dom->getElementsByTagName('row');
  2. 如果[A-Z]{1}\d{2}C,匹配內部rownodeValue,輪胎是新的
  3. childNodes的的,直到我們找到localName =
  4. 更改childnodeValue這是上面的匹配 +現有nodeValue

$dom = new DOMDocument(); 
$dom->loadXML(file_get_contents("file.xml")); 
$rows = $dom->getElementsByTagName('row'); 
foreach($rows as $row){ 
    if (preg_match('/[A-Z]{1}\d{2}C/', $row->nodeValue)){ 
    foreach($row->childNodes as $child) { 
     if($child->localName == "type"){ 
      $child->nodeValue = "new ".$child->textContent; 
     } 
     } 
    } 
} 
echo $dom->saveXML(); 

Ideone Demo

0

當您使用SimpleXML的,你不需要擔心DOM操作和可以把你的XML對象作爲一個StdClass

$filename = "./mos-test2.xml"; 
$data = simplexml_load_file($filename); 

foreach ($data as $row) { 
    if (preg_match("/R\d{2}C/", $row->name) === 1) { 
     $row->type = 'new ' . $row->type; 
    } 
} 

$str = $data->asXML(); 

因爲它是在名字說,的SimpleXML保持事情很簡單。

0

謝謝大家!

此代碼對我的作品

<? 
$dom = new DOMDocument(); 
$dom->loadXML(file_get_contents("./mos-test2.xml")); 
$rows = $dom->getElementsByTagName('row'); 
foreach($rows as $row){ 
if (preg_match('/[A-Z]{1}\d{2}C/', $row->nodeValue)){ 
    foreach($row->childNodes as $child) { 
     if($child->localName == "type"){ 
      $child->nodeValue = "Легкогрузовые"; 
     } 
     } 
    } 
} 
$dom->encoding = 'UTF-8'; 
$dom->save("./mos-test-ready.xml") 
?>