gpt4 book ai didi

php - 如何在 php 中打开一个文件

转载 作者:行者123 更新时间:2023-12-02 07:40:01 25 4
gpt4 key购买 nike

我已经查找过有关此主题的问题,但未能找到我要查找的内容。 This is for C++ ,我需要类似的 PHP。 This is for including php files ,我只想读取一个 CSV 文件。

我有这个:

if(file_exists("data.csv")){
echo "CSV file found";

$csv_data = file_get_contents("data.csv");

$lines = explode("\n", trim($csv_data));

$array = array();

foreach ($lines as $line){
$array[] = str_getcsv($line);

}else {echo "File not found";}

但我不想指定文件名 - 即一般加载/读取/打开文件。

这样做有什么简单的原因吗?没有意义,但我被告知不要在我的 PHP 脚本中进行任何硬编码。

提前致谢。

最佳答案

使用fgetcsv

if(file_exists("data.csv")){
echo "CSV file found";
$handle = fopen("data.csv", "r");
if(!$handle) die("Could not open file!");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);

}else {echo "File not found";}

关于php - 如何在 php 中打开一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12179871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com