使用PHP过滤和显示CSV文件 [英] Filtering and displaying a CSV file with PHP
问题描述
我目前正在使用PHP检索CSV文件,并通过以下方法以表格格式显示该文件:
I am currently retrieving a CSV file with PHP and displaying it in a table format via the following method:
<?php
if (($file_handle = fopen("data.csv", "r")) !== false) {
$str = '';
$str .= '<table>';
while (($data = fgetcsv($file_handle, 1024, ",")) !== false) {
$str .= '<tr>';
foreach ($data as $key => &$value) {
$str .= "<td valign='top'>$value</td>";
}
$str .= '</tr>';
$str .= '<tr><td><br></td></tr>';
}
fclose($file_handle);
$str .= '</table>';
echo $str;
}
?>
这很好,很简单.但是,我只想在CSV文件中的行包含特定值时显示该行.我一直在努力寻求解决方法,但是我对CSV操作的熟悉程度还不足以使一切正常.谁能指出我正确的方向?
This works fine and is nice and straight forward. However, I would like to only display rows from the CSV file when that row contains a specific value. I've been trying to get my head around how I can do this, but I'm not familiar enough with CSV manipulation to get anything working. Can anyone point me in the right direction?
例如,假设我的CSV文件的结构如下
As an example, say my CSV file is structured like this
Timestamp, F, staff, kitchen, 34
Timestamp, P, staff, floor, 32
Timestamp, F, staff, floor, 33
Timestamp, F, contractor, kitchen, 65
Timestamp, P, staff, kitchen, 34
如果我只想输出最终值为例如34的行,我该怎么做?
If I only want to output rows where the final value is, for example, 34, how would I do this?
推荐答案
您可以使用简单的continue语句跳过行.例如
You can skip rows with simple continue statement. For example
<?php
if (($file_handle = fopen("data.csv", "r")) !== false) {
$str = '';
$row = 0;
$str .= '<table>';
while (($data = fgetcsv($file_handle, 1024, ",")) !== false) {
$row++;
if ($data[4] != '34' && $row > 1) continue; // *** skip rows without '34' ***
$str .= '<tr>';
foreach ($data as $key => &$value) {
$str .= "<td valign='top'>$value</td>";
}
$str .= '</tr>';
$str .= '<tr><td><br></td></tr>';
}
fclose($file_handle);
$str .= '</table>';
echo $str;
}
?>
这篇关于使用PHP过滤和显示CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!