This is my php code and it is supposed to write a csv file, but the output file contains unreadable letters and symbols. What should I do so that the information is written in Persian letters?
<?php
// Get RSS feed URL from form data
$rss_url = $_POST['rss-url'];
// Create SimpleXMLElement object from RSS feed
$rss = new SimpleXMLElement(file_get_contents($rss_url));
// Open CSV file for writing
$filename = 'rss-data.csv';
$file = fopen($filename, 'w');
// Write header row to CSV file
$header_row = array('Title', 'Description', 'PublicationDate', 'Link', 'Photo');
fputcsv($file, $header_row);
// Loop through RSS feed items
foreach ($rss->channel->item as $item) {
// Extract data from item
$title = mb_convert_encoding((string) $item->title, 'UTF-8', 'ISO-8859-1');
$description = mb_convert_encoding((string) $item->description, 'UTF-8', 'ISO-8859-1');
$pub_date = mb_convert_encoding((string) $item->pubDate, 'UTF-8', 'ISO-8859-1');
$link = mb_convert_encoding((string) $item->link, 'UTF-8', 'ISO-8859-1');
preg_match('/<img.*?src="(.*?)".*?>/is', $description, $matches);
$image = isset($matches[1]) ? $matches[1] : '';
// Write data to CSV file
$data_row = array($title, strip_tags($description), $pub_date, $link, $image);
fputcsv($file, $data_row);
}
// Close CSV file
fclose($file);
// Redirect to index.html
header('Location: index.html');
exit();
?>
My php code should write a CSV file with persian letters in this.
You should use the following code at the start.
header('Content-Type: text/html; charset=UTF-8');
setlocale(LC_ALL, 'fa_IR.utf8');
Here is your full modified code.
<?php
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=UTF-8');
setlocale(LC_ALL, 'fa_IR.utf8');
// Get RSS feed URL from form data
$rss_url = $_POST['rss-url'];
// Create SimpleXMLElement object from RSS feed
$rss = new SimpleXMLElement(file_get_contents($rss_url));
// Open CSV file for writing
$filename = 'rss-data.csv';
$file = fopen($filename, 'w');
// Set the encoding of the CSV file to UTF-8
fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
// Write header row to CSV file
$header_row = array('Title', 'Description', 'PublicationDate', 'Link', 'Photo');
fputcsv($file, $header_row);
// Loop through RSS feed items
foreach ($rss->channel->item as $item) {
// Extract data from item
$title = htmlspecialchars_decode((string) $item->title, ENT_QUOTES | ENT_XML1);
$description = htmlspecialchars_decode((string) $item->description, ENT_QUOTES | ENT_XML1);
$pub_date = (string) $item->pubDate;
$link = (string) $item->link;
preg_match('/<img.*?src="(.*?)".*?>/is', $description, $matches);
$image = isset($matches[1]) ? $matches[1] : '';
// Write data to CSV file
$data_row = array($title, $description, $pub_date, $link, $image);
fputcsv($file, $data_row);
}
// Close CSV file
fclose($file);
// Redirect to index.html
header('Location: index.html');
exit();
?>