PHP创建一个CSV文件并用波斯语写

ljsrvy3e  于 2023-07-31  发布在  PHP
关注(0)|答案(1)|浏览(86)

这是我的php代码,它应该写一个csv文件,但输出文件包含不可读的字母和符号。我该怎么做才能让信息用波斯字母写出来?

<?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();
?>

字符串
我的php代码应该写一个CSV文件与波斯字母在此。

raogr8fs

raogr8fs1#

您应该在开始时使用以下代码。

header('Content-Type: text/html; charset=UTF-8');
setlocale(LC_ALL, 'fa_IR.utf8');

字符串
这是你修改过的完整代码。

<?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();
?>

相关问题