这是一个完全实验性的问题,但如果得到回答,它将节省我数小时的手动HTML标记。
理论上它应该有效,但如果我说的是垃圾,可以提供建议。
我需要一个循环来从CSV电子表格中的列中提取列数据,并在HTML标记中回显它们。
我无法编写PHP,但这就是我设想循环工作的方式......
<?php
// here it needs to load the CSV file and get the column data and output them as variables (I guess)
echo <div id="interactive-map">
// here a loop needs to begin to output this line off HTML...
// with the arrayed variables...
<div id="[varible-1]" class="[varible-2]" title="[varible-3]"><span>[varible-3]</span></div>
// loop finished once no more rows left in CSV
echo </div>
?>
所以结果应该是这样......
<div id="interactive-map">
<div id="1" class="free" title="Uber"><span>Uber</span></div>
<div id="2" class="free" title="Howdy"><span>Howdy</span></div>
<div id="3" class="free" title="Love"><span>Love</span></div>
<div id="4" class="free" title="Gimme"><span>Gimme</span></div>
<div id="5" class="free" title="Totally"><span>Totally</span></div>
<div id="6" class="free" title="Spank"><span>Spank</span></div>
</div>
CSV文件看起来像这样......
http://www.motocom.co.uk/test/varible.jpg
任何帮助或建议都会令人惊叹!感谢
//下面的第一个答案后更新
我的CSV下面被视为文字...
id,class,name
1,free,Uber
2,free,Howdy
3,free,Love
4,free,Gimme
5,free,Totally
6,free,Spank
下面的PHP ......
<?php
$file = fopen('file.csv', 'r');
$fields = array();
if ($file) {
while (($data = fgetcsv($file)) !== false) {
if(empty($fields)) {
$fields = $data;
continue;
}
$row = array_combine($fields, $data);
$output = sprintf("% is ID, % is CLASS, % is NAME",
$row['id'],
$row['class'],
$row['name']);
echo $output;
}
fclose($file);
}
?>
它运作不正常,我做错了什么?
关于添加HTML,我将标记放在回显文本所在的位置并且混淆了: - /
这是回声,但不是来自csv的所需信息。
答案 0 :(得分:2)
要读取文件,最简单的方法是在循环中使用内置fgetcsv
。你可以编写自己的解析代码,但是如果在字段分隔符和转义字符存在的情况下使其正常运行,那真是吃力不讨好。
在读取CSV字段的名称(第一次迭代)及其每行的值(后续迭代)之后,您可以使用sprintf
或vsprintf
轻松构造要输出的HTML字符串。 / p>
例如:
$file = fopen('php://stdin', 'r'); // or open any other file you want
$fields = array(); // this holds the name of the fields, read from the 1st row
if ($file) {
while (($data = fgetcsv($file)) !== false) {
// If this is the first row, we assume it holds field names.
// So just remember what they are and loop to the next.
if(empty($fields)) {
$fields = $data;
continue;
}
// Subsequent rows are assumed to contain data.
// array_combine associates the data in the current row with the field
// names from the first row, allowing us to refer to them using those
// names and be independent of the order the fields appear in the input.
$row = array_combine($fields, $data);
// Format output conveniently with sprintf
$output = sprintf("%s is %d years old.\n",
$row['name'],
$row['age']);
echo $output;
}
fclose($file);
}
<强> See it in action 强>