我有一个Csv文件:
我想将此文件转换为数组以创建多个消息字符串。
// Parse the csv into array
$csv = array_map('str_getcsv', file('metu2.csv'));
// Remove first array as it is the Column Titles
array_shift($csv);
$message = "Dear [F1], Please pay Rs [F2] thanks"; // Declare message
// Loop thru each array and echo message
foreach($csv as $array) {
echo str_replace("[F1]","$array[1]", $message);
echo '<br>';
}
//Output:
// Dear John, Please pay Rs [F2] thanks
// Dear Rita, Please pay Rs [F2] thanks
// Dear Tom, Please pay Rs [F2] thanks
// Dear Tony, Please pay Rs [F2] thanks
// Dear Zebra, Please pay Rs [F2] thanks
如何同时更换[F2]?
答案 0 :(得分:0)
您可以使用str_getcsv()
将csv文件解析为数组。您可以使用array_map
$message = "Dear %s, Please pay $ %d."; // Declare message
// Parse the csv into array
$csv = array_map('str_getcsv', file('mobile.csv'));
// Remove first array as it is the Column Titles
array_shift($csv);
// Loop thru each array and echo message
foreach($csv as $array) {
echo sprintf($message, $array[1], $array[2]);
echo '<br>';
}
如果你真的在使用str_replace()
。将foreach循环函数更改为类似
$message = "Dear [F1], Please pay Rs [F2] thanks"; // Message
foreach($csv as $array) {
$search = array("[F1]", "[F2]"); // Strings to search
$replace = array($array[1], $array[2]); // Values to place
echo str_replace($search, $replace, $message); // str_replace function
echo '<br>';
}
搜索和替换数组对应于它的相应索引。
e.g。 $search[0]
替换为$replace[0]
答案 1 :(得分:0)
您最好使用sprintf
(http://php.net/manual/fr/function.sprintf.php)代替str_replace。
您可以使用以下内容轻松完成所需内容:
<?php
$message = "Dear %s, \n Please pay %d.";
if (($handle = fopen("your-file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, " ")) !== FALSE) {
echo sprintf($message, $data[1], $data[2]) . "<br/>";
}
fclose($handle);
}
?>