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.
Related
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!
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
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
Following is the code, i am trying to format the data extracted from the xml file into csv.By default its inserted row wise. I am trying to make it presentable and easy to interpret.
I am not a professional coder so please excuse me if my solution is not an optimised one.
<?php
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="DynaMedResult.csv"');
//Using esearch utility capture WebEnv variable
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=DynaMed&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context); //Reads entire file into a string
$xml = simplexml_load_string($xml);
foreach ($xml->WebEnv as $WebenvSearch){
$WebEnv=$WebenvSearch;
}
//Using efetch utility and passing WebEnv variable parse the xml
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&term=DynaMed&WebEnv=$WebEnv&query_key=1&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml); //Interprets a string of XML into an object
$fp = fopen('php://output', 'w');
foreach ($xml as $pubmedst){
$article=$pubmedst->MedlineCitation->Article->ArticleTitle;
$pmid=$pubmedst->MedlineCitation->PMID;
$journal1=$pubmedst->MedlineCitation->MedlineJournalInfo->MedlineTA;
$journal2=$pubmedst->MedlineCitation->MedlineJournalInfo->NlmUniqueID;
$pubyear=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Year;
$pubmonth=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Month;
$pubday=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Day;
$authorl=$pubmedst->MedlineCitation->Article->AuthorList->Author->LastName;
$authorf=$pubmedst->MedlineCitation->Article->AuthorList->Author->ForeName;
$authori=$pubmedst->MedlineCitation->Article->AuthorList->Author->Initials;
$val1 = explode("\n", $article);
fputcsv($fp, $val1); //Format line as CSV and write to file pointer
$val2 = explode("\n", $pmid); //Splits a string by string in our case a newline
fputcsv($fp, $val2);
$val3 = explode("\n", $journal1.=$journal2);
fputcsv($fp, $val3);
$val4 = explode("\n", $authorl.=$authorf);
fputcsv($fp, $val4);
$val5 = explode("\n", $pubyear.=$pubmonth);
fputcsv($fp, $val5);
}
fclose($fp);
?>
As per the fputcsv() documentation, fputcsv() expects to be given an ARRAY of data to be output as csv data. You're passing in individual strings, so each string becomes a single "field" in a 1-column CSV file.
You need to build an array of data, then output the array:
$data[0] = 'foo';
$data[1] = 'bar';
$data[2] = 'baz';
fputcsv($fp, $data);
will produce
foo,bar,baz
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