如何获取CSV文件的行数与单元格数?PHP读取CSV后需统计记录数
Hey there! Let's break down your two CSV questions with practical, reliable solutions—whether you're using command-line tools or PHP:
CSV files can have tricky edge cases (like cells with wrapped newlines or commas), so I’ll cover both simple and robust methods.
Command-Line Tools (Quick for Non-PHP Scenarios)
Counting rows
- For simple CSVs (no wrapped newlines): Use
wc -l yourfile.csv—just remember to subtract 1 if your CSV has a header row to get the actual record count. - For robust counting (handles wrapped newlines in quoted cells):
This cleans up newlines inside quoted cells before counting total rows.awk -F '"' '{for(i=2;i<=NF;i+=2) gsub(/\n/," ",$i)} END{print NR}' yourfile.csv
- For simple CSVs (no wrapped newlines): Use
Counting total cells
- Simple case (no quoted commas/newlines):
awk -F ',' '{sum+=NF} END{print sum}' yourfile.csv - Robust case (handles quoted content):
This first neutralizes commas inside quotes, then counts columns per row and sums them up.awk -F '"' '{for(i=2;i<=NF;i+=2) gsub(/,/," ",$i)} {print NF-((NF-1)/2)}' yourfile.csv | awk '{sum+=$1} END{print sum}'
- Simple case (no quoted commas/newlines):
Since you’re already using PHP to read and print CSV content, let’s integrate record counting seamlessly. I’ll assume your current code looks something like this (using fgetcsv, the most reliable method for CSVs):
$file = fopen('yourfile.csv', 'r'); // Skip header if your CSV has one fgetcsv($file); while (($row = fgetcsv($file)) !== FALSE) { // Print row content print_r($row); } fclose($file);
Here are the best ways to add record counting:
Method 1: Increment a Counter in the Loop (Best for All File Sizes)
This is the most memory-efficient approach, especially for large CSVs, since it reads one row at a time:
$file = fopen('yourfile.csv', 'r'); $recordCount = 0; // Skip header if applicable $header = fgetcsv($file); while (($row = fgetcsv($file)) !== FALSE) { // Print your row content as before print_r($row); // Increment counter for each valid record $recordCount++; } fclose($file); echo "<br>Total records: " . $recordCount;
Why this works: fgetcsv correctly parses cells with wrapped newlines, so your count will be accurate even with tricky CSV formatting.
Method 2: Read All Rows into an Array (For Small CSVs Only)
If your CSV is small enough to fit in memory, you can load all rows at once and count:
$csvContent = file_get_contents('yourfile.csv'); // Split into rows (note: this fails if cells have wrapped newlines!) $rows = str_getcsv($csvContent, "\n"); // Remove header row if present array_shift($rows); $recordCount = count($rows); // Print each row's content foreach ($rows as $rowLine) { $rowData = str_getcsv($rowLine); print_r($rowData); } echo "<br>Total records: " . $recordCount;
Warning: Avoid this for large files or CSVs with wrapped newlines—it’ll miscount rows and use unnecessary memory.
内容的提问来源于stack exchange,提问作者user9345281

