I have a link to an online XML file that contains different values. I have written a code that allows me to retrieve the contents of two specific tags in this file and put them in a csv file.
The first tag is the :
<g:id>...</g:id>
And the second one is a url with :
<g:link>...</g:link>
My problem is that in the output csv file I do get the urls but they are put in columns and the id does not get put in my csv file :
How can I do please to have the output file like this?
<?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); ?>
Advertisement
Answer
you could use SimpleXML to parse the XML and find data, instead of trying to search in XML string.
Note that fputcvs()
takes an array as second argument.
$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);
Will generate a CSV file like this :
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