John Davidson

php - fputcsv setting semicolon delimiter

0 comments
Message:


I am able to grab the data returned from a stored procedure and set it to an array.


After that, I am opening a file path to upload a file.


The file was spitting out a text file with a comma delimiter.


I found that you can use fputcsv to set the delimiter to a semicolon.


Here is my attempt, starting with the SP call:


<?php
$filename = 'myFile';

$thecall = mysqli_query($dbc, "CALL SP_SVC($servicecodes)");

if($thecall){
$out = array();

while($row = $thecall->fetch_assoc()){
$out[] = $row;
}

$file = fopen("//folderName/IS/business/reports/TXT Report files/$filename.txt", 'w');
foreach($out as $fields){
fputcsv($file, explode(';',$fields), ";");
}
}
?>

Using the above, I am getting an error in the console that reads:


Warning:  explode() expects parameter 2 to be string, array given in 
D:\htdocs\mySite\api\serviceReport.php on line 99

Warning: fputcsv() expects parameter 2 to be array, null given in
D:\htdocs\mySite\api\serviceReport.php on line 99

Line 99 is where the fputcsv function is located.


In the foreach loop, I tried to echo out the $fields variable, and I get the following error:


Notice:  Array to string conversion in D:\htdocs\mySite\api\serviceReport.php on line 99

What am I doing wrong, and how can I set the delimiter to a semicolon?



My Answer:
php
// Call stored procedure and fetch data
$stmt = $pdo->prepare("CALL your_stored_procedure()");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Open file for writing
$fp = fopen('path/to/file.csv', 'w');

// Set delimiter to semicolon
$delimiter = ';';

// Write data to file with semicolon delimiter
foreach ($data as $row) {
fputcsv($fp, $row, $delimiter);
}

// Close file
fclose($fp);


This code snippet demonstrates how to use fputcsv to set the delimiter to a semicolon when writing data to a CSV file. Make sure to replace `your_stored_procedure()` with the actual name of your stored procedure and `path/to/file.csv` with the desired file path.

Rate this post

3 of 5 based on 1809 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us