【问题标题】:XML to CSV with value change值更改的 XML 到 CSV
【发布时间】:2020-10-05 14:24:04
【问题描述】:

我想通过替换一些值将 XML 转换为 CSV 文件。 为了简单的转换,我使用了这个脚本:

$xml_file_input='file.xml';
$csv_file_output = 'file.csv';
function convertXmlToCsvFile($xml_file_input, $csv_file_output) {
    $xml = simplexml_load_file($xml_file_input);
    $output_file = fopen($csv_file_output, 'w');
    $header = false;
    foreach($xml as $key => $value){
        if(!$header) {
            fputcsv($output_file, array_keys(get_object_vars($value)));
            $header = true;
        }
        fputcsv($output_file, get_object_vars($value));
    }
    fclose($output_file);
}
convertXmlToCsvFile($xml_file_input,$csv_file_output);

例如 XML 中的值

“新红地毯 130x200”

在 CSV 中我想拥有

“新地毯 130x200”

XML 内容:

<offers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1">
<script/>
<offer>
<title>New red carpet 130x200</title>
<price>123</price>
</offer>
<offer>
<title>New green carpet 170x300</title>
<price>234</price>
</offer>
</offers>

如果有任何帮助,我将不胜感激!

【问题讨论】:

  • 假设转换为 csv 不是问题,你能用 xml 的代表性样本编辑你的问题吗?
  • 已编辑。我被添加了 xml 内容

标签: php xml csv


【解决方案1】:

要解决修改目标元素文本内容的具体问题,可以试试这样的:

$targets = $xml->xpath('//offer/title[text()="New red carpet 130x200"]');
foreach ($targets as $target) 
    $target[0] = "Another Carpet";
echo $xml->asXML();

输出:

<?xml version="1.0"?>    
<offers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1">    
<script/>    
<offer>    
<title>Another Carpet</title>    
<price>123</price>    
</offer>    
<offer>    
<title>New green carpet 170x300</title>    
<price>234</price>    
</offer>    
</offers>

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 2021-12-24
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多