I have a line of data stored in $StripContent, when I echo $Stripcontent it shows
, , ,1 ,1415 ,Fietsen ,Omafietsen ,Avalon ,F 101 Oma Export 57cm Zwart , ,57 ,single speed remnaaf ,2017 ,21 ,249.00 ,135.00 ,19.50 ,8
However when I write $Stripcontent to the CSV file it only writes the first character instead of the whole line.
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
foreach($content as $lineNumber => &$lineContent) {
if($lineNumber == 0) {
$lineContent .= $StripContent . PHP_EOL;
}
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);
You can do it more direct with the $Stripcontent variable direclty, whithout the foreach part, like:
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
file_put_contents($file, $Stripcontent);
This works if you want to store the stripContent string. I recomend you to wrap it between a try{...}catch() and check for folder permisions to avoid problems!
Or if you want to use the built-in function for CSV you can use fputcsv (offical documentation):
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Hope it helps!
Related
I am running an API, the response of this API is returning response in comma separated values.
I am returning response in $result.
Response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type 106864,new,"Gift Vouchers worth ₹2000 # for just ₹999","Get it for just ₹999",,"Gift Items","ABC Company",http://example1.com,http://example2.com,"2016-04-07 00:00:00","2016-05-01 00:00:00",sale
Below are the headers in response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type
Code I have tried:
function str_putcsv($result) {
# Generate CSV data from array
$fh = fopen('php://temp', 'rw'); # don't create a file, attempt
# to use memory instead
# write out the headers
fputcsv($fh, array_keys(current($result)));
# write out the data
foreach ( $result as $row ) {
fputcsv($fh, $row);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
return $csv;
}
With the code above I am not able to find where this code is generating CSV.
Another code:
$fp = fopen('data.csv', 'w');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
Above code is generating file on FTP but there is no data in it. It is generating blank CSV.
I want to convert this response into CSV file and put it on a FTP or in the same directory.
You can just put everything in an array. And use int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
Example from php.net:
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('path/to/file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
read more about fgetcsv here
How should I use tabulate?
$naglowek = "ID,\t Imię,\t Nazwisko,\t Data urodzenia,\t Miasto,\t EMAIL";
$naglowek = explode(";",$naglowek); // header
fputcsv($fp, $naglowek);
while($r = $result->fetch_assoc()){
$ciag = '';
$ciag = $r['id'].','.$r['name'].','.$r['surName'].','.$r['dateOfBirth'].','.$r['city'].','.$r['email'];
$ciag = explode(";",$ciag);
fputcsv($fp, $ciag,"\t");
}
I added "\t" but it isn't working.
Below is question, what somebody answered.
I made a CSV generator for my client. It should get data from DB (mysqli).
The code is :
while($r = $result->fetch_assoc()){
$someVariable = $r['id'].','.$r['name'].','.$r['surName'].','.$r['dateOfBirth'].','.
$r['city'].','.$r['email'];
}
It is working. But I go to next step to use a function fputcsv. It is from PHP5.
This is how my DB looks:
In PHPManual fputcsv is using like:
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
How can I use my data to this array ? My data will be from DataBase and will be generated dynamically by the loop above.
You can do that in this way:
$fp = fopen('out.csv', 'w');
while($r = $result->fetch_assoc()){
fputcsv($fp, $r);
}
fclose($fp);
For each line that fetch from the database, it will include in out.csv file.
I have this JSON:
{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}
How to convert this to CSV file or Exel XLS using php pdo?
Also in this example:
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));
}
where I need to put my $jsonTable ?
Use JSON2CSV
A simple PHP script to convert JSON data to CSV
example usage:
php json2csv.php --file=/path/to/source/file.json --dest=/path/to/destination/file.csv
OR You can have it dump the CSV file relative to the PHP script:
php json2csv.php --file=/path/to/source/file.json
I am not sure about the pdo part, but to write it to a file you would do something like this
$json = '{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}';
$out = fopen('file.csv', 'w');
foreach(json_decode($json, true)['data'] as $key => $value) {
fputcsv($out, $value);
}
fclose($out);
Is possible in a webpage create a button that export a specific table with PHP?
Example: I click the button "Export Contacts" and this call a function that return me a .csv file of the table "contacts", for example.
Here is the simple way to export the data to csv file. You can use this.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Here is the link http://www.php.net/manual/fr/function.fputcsv.php
I have a script that copys results from a table and saves it in a csv format. Everything is running fine with the script except that it does not recognize \n and just inputs it in the last cell like blahblah\r\n.
I have these lines currently but neither situation is creating the new line...-
$csv_output .= "$lastName,$firstName,$agentMLSID,$agentBoard,$directOffice,$directOfficeExtension,$voicemail,$mobile,$email,$officeName ".PHP_EOL;
$csv_hdr = "lastname,firstname,mslid,board,directline,ext,vm,mobile,email,office";
$csv_hdr .= "\n";
fputcsv() is what you need.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Output (file.csv):
aaa,bbb,ccc,dddd
123,456,789