首页 > 解决方案 > 如何将 XML 文件中的值添加到 php 中的 csv 文件?

问题描述

我有一个指向包含不同值的在线 XML 文件的链接。我编写了一个代码,允许我检索此文件中两个特定标签的内容并将它们放入 csv 文件中。

第一个标签是:

<g:id>...</g:id>

第二个是一个网址:

<g:link>...</g:link>

我的问题是,在输出 csv 文件中,我确实得到了 url,但它们被放在列中,并且 id 没有放在我的 csv 文件中:

在此处输入图像描述

我该怎么做才能有这样的输出文件?

在此处输入图像描述

<?php

  //Function for split string
  function multiSplit($string)
  {
      $output = array();
      $cols = explode("<g:image_link>", $string);

        foreach ($cols as $col)
        {
            $dashcols = explode("</g:image_link>", $col);
            $output[] = $dashcols[0];
        }
  
    return $output;
}


 //Function for split string
 function multiSplit2($string)
 {
     $output = array();
     $cols = explode("<g:id>", $string);

     foreach ($cols as $col)
        {
            $dashcols = explode("</g:id>", $col);
            $output[] = $dashcols[0];
        }
        
     return $output;
}


$html = file_get_contents('https://www.ripcurl.eu/assets/fb_product_feed_eur.xml');


$url = multiSplit($html);
$id = multiSplit2($html);

$idfinal = $id[1].'-RC';

print_r($idfinal); //BDGTP6-RC
echo '<br>';
print_r($url[1]); //https://dwk1ydkfsczz3.cloudfront.net/images/2020/06/15/BDGTP6-0070-1jpg-051717be-657e-4f08-9d75-914926540fd4.jpg


$name = "BI4_".date('Ymd_His').".csv";
$cheminfile = "C:/wamp64/www/retail_BI/".$name;

$fp = fopen("$cheminfile", "w");

$delimiter = ';';

    fputcsv($fp, array('stylecode', 'images'), $delimiter);
    
    foreach ( $url as $ur ) {
            
            fputcsv($fp, $url, $delimiter);
            
        }
        
fclose($fp);

?>

标签: phpcsv

解决方案


您可以使用SimpleXML解析 XML 并查找数据,而不是尝试在 XML 字符串中进行搜索。

请注意,fputcvs()将数组作为第二个参数。

$delimiter = ';';
$fp = fopen($cheminfile, "w");
$xml = simplexml_load_file('https://www.ripcurl.eu/assets/fb_product_feed_eur.xml');
fputcsv($fp, array('stylecode', 'images'), $delimiter);

// loop over items in "channel"
foreach ($xml->channel->item as $item) 
{
    // get values for `g:` namespace
    $children = $item->children("http://base.google.com/ns/1.0");
          
    // get id and link
    $id = (string) $children->id;
    $link = (string) $children->image_link;

    // add values to CSV
    fputcsv($fp, [$id, $link], $delimiter);
}
fclose($fp);

将生成一个这样的 CSV 文件:

stylecode;images
BDGTP6;https://dwk1ydkfsczz3.cloudfront.net/images/2020/06/15/BDGTP6-0070-1jpg-051717be-657e-4f08-9d75-914926540fd4.jpg
CFEBL9;https://dwk1ydkfsczz3.cloudfront.net/images/2020/08/03/CFEBL9-0090-1jpg-a9bd9dda-a775-4b4f-af00-3dcbf261bc2d.jpg

推荐阅读