php - 如何将 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);
?>
解决方案
您可以使用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
推荐阅读
- php - 在 wordpress 内容中查找和替换 url
- javascript - 如何检测触摸和鼠标的滑动并找到滑动方向
- java - Admob 初始化失败,App 启动时崩溃,即使没有错误
- ubuntu - 无法在 Ubuntu 上找到包 php8.0
- java - @RequestParam defaultValue 覆盖用户输入
- azure-data-factory - 如何使用 .net sdk 在 Adf 复制活动中使用查询?
- ethereum - 如何将拍卖功能真正融入我的 daap?
- apache-flink - 将自定义数据添加到 Flink 指标
- python - 如何在 Pydroid 3 中捕获应用程序发送的数据?
- javascript - Axios Put 不更新 Value