我一直在寻找关于这个主题的问题,但没有得到我想要的东西。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脚本中硬编码任何东西。
提前谢谢。
发布于 2012-08-29 22:22:18
如果您的脚本中可能没有硬编码的内容,则需要将这些硬编码的内容放入某种外部配置文件中。您必须将该配置文件的名称硬编码到您的bootstrap或应用程序中最先出现的任何文件中。加载配置后,在需要的地方提供配置数据。不将配置数据硬编码到代码中将允许您创建更多可重用的组件和代码,例如,CSV Reader可以读取任何CSV文件,而CSV Reader只能读取其中硬编码的一个特定CSV文件。
示例:
// config.php
<?php
return array(
'csvFile' => '/path/to/file.csv',
…
);
// bootstrap.php
<?php
$config = include '/path/to/config.php';
…
// someFile.php
<?php
include '/path/to/bootstrap.php';
$file = new SplFileObject($config['csvFile']);
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
// Do something with values
}发布于 2012-08-29 22:13:30
使用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";}发布于 2012-08-29 22:12:52
将你的代码放入一个函数中...
function open_file($file_name)
{
if (!file_exists($file_name))
{
return false;
}
$csv_data = file_get_contents($file_name);
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line)
{
$array[] = str_getcsv($line);
}
return $array;
}https://stackoverflow.com/questions/12179871
复制相似问题