如何根据预设参数查找和替换XML中的值


How to find and replace the value in XML according to preset parameters

请告知。我有XML,需要通过php进行更正。

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>

结果是,如果<name></name>中有类似"R16C"(或R12C、R13C等)的值,我需要将<type>car tires</type>替换为<type>new car tires</type>。符号"C"表示"新车轮胎"类型。否则,不更改字段名。

我收到错误"为xml parser.php中的foreach()提供的参数无效"

该怎么办,请通知

  $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);
  1. 获取所有行节点$dom->getElementsByTagName('row');
  2. 如果[A-Z]{1}'d{2}C,与row内的nodeValue匹配,则轮胎为新轮胎
  3. 循环rowchildNodes,直到我们找到localName=类型
  4. 将上面匹配的child nodeValue更改为新的+现有的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演示

当您使用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使事情变得简单。

感谢大家!

这个代码适用于我

<?
$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")
?>