I generate an array of several variables and want to write entirely this into a csv-file. The header works correctly but from the array only /\n/"(, is written into the csv.
If I use implode
before echo, then I get an empty line.
What's wrong? here is the code I'm using so far:
<?php
function scrape_between($data, $start, $end){
$data = stristr($data, $start);
$data = substr($data, strlen($start));
$stop = stripos($data, $end);
$data = substr($data, 0, $stop);
return $data;
}
function curl($url) {
$options = Array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_AUTOREFERER => TRUE,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8", // Setting the useragent
CURLOPT_URL => $url,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
curl_close($ch);
return $data;
};
$header = 'date1,date2,contractcode,exchange,region,commoditycode,openint,noncomlong,noncomshort,noncomspread,comlong,comshort,';
echo($header);
$scraped_page = curl("https://www.cftc.gov/dea/newcot/deafut.txt");
$scraped_wheat = scrape_between($scraped_page, "WHEAT-SRW - CHICAGO BOARD OF TRADE", "CONTRACTS");
$scraped_wheat = preg_replace('/",/', '', $scraped_wheat);
$pieces = explode('WHEAT', $scraped_wheat);
$items = explode(",",$pieces[0]);
$tmp = 0;
foreach ($items as $value)if ($tmp++ < 12) {
$value = preg_replace('/\s/', '', $value);
echo ($value.",");
};
$file = 'cot-zw.csv';
file_put_contents($file, $header.'/\n/'.$value.",");
?>
Thank you very much for your help!
EDIT
The suggestions via fputcsv
produces an empty csv-file. Thats what I tried (and failed):
$scraped_wheat = scrape_between($scraped_page, "WHEAT-SRW - CHICAGO BOARD OF TRADE", "CONTRACTS");
$scraped_wheat = preg_replace('/",/', '', $scraped_wheat); // ", am Anfang entfernen
$pieces = explode('WHEAT', $scraped_wheat); // explode() Teilt die Zeichenkette
$items = explode(",",$pieces[0]); // Definition des , als Teiler
$tmp = 0;
foreach ($items as $value)if ($tmp++ < 12) {
$value = preg_replace('/\s/', '', $value);
echo ($value.",");
$fp = fopen('cot-zw.csv', 'w');
foreach($value as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
};```