How can a CSV file be created and written to in PHP, based on data retrieved from a URL?
To create and write data to a CSV file in PHP based on data retrieved from a URL, you can use functions like file_get_contents() to fetch the data from the URL, then parse and format it as needed before writing it to a CSV file using fputcsv().
<?php
// Retrieve data from URL
$url = 'https://example.com/data.csv';
$data = file_get_contents($url);
// Parse data as needed
$rows = explode("\n", $data);
$csvData = [];
foreach ($rows as $row) {
$csvData[] = str_getcsv($row);
}
// Write data to CSV file
$csvFile = fopen('output.csv', 'w');
foreach ($csvData as $row) {
fputcsv($csvFile, $row);
}
fclose($csvFile);
echo 'CSV file created and data written successfully!';
?>
Keywords
Related Questions
- What potential issues can arise when sending and receiving data from a server using fsockopen in PHP?
- What are some best practices for debugging issues related to variable passing in PHP?
- What are the potential pitfalls of using different types of quotation marks in PHP code and how can they impact functionality?