PHP循环读取CSV文件部分行丢失问题排查与修复求助
Let's break down what's causing the missing/skipped tickers and fix it step by step.
Root Causes of the Issue
Broken CSV Reading Logic
Your original code usesexplode("\r", $line[0])to split each line, which creates empty elements in the$tickersarray when lines have trailing carriage returns (\r). These empty elements take up spots in your slices, making it look like valid tickers are being skipped. You also weren't filtering out empty lines from the CSV, which added more invalid entries.Rigorous Loop Condition
Theforloop's upper limit(int)(count($tickers)/$delta)doesn't handle non-integer divisions cleanly, especially when there are empty elements inflating thecount($tickers)value. This can cause the final batch of tickers to be omitted.
Fixed Code
First, fix the CSV reading to ensure we only get valid, clean ticker symbols:
<?php $tickers = array(); $f = fopen("all.csv", "r"); // Let PHP auto-detect line endings for cross-system compatibility ini_set('auto_detect_line_endings', true); while (($line = fgetcsv($f)) !== false) { // Clean up the ticker string (remove \r, \n, and extra whitespace) $ticker = trim($line[0]); // Only add non-empty, valid tickers to the array if (!empty($ticker)) { $tickers[] = $ticker; } } fclose($f); ?>
Then, rewrite the widget generation loop to reliably process all tickers:
<?php $delta = 11; $start = 0; $totalTickers = count($tickers); // Loop until we've processed all tickers (handles non-integer delta divisions perfectly) while ($start < $totalTickers) { // Grab up to $delta tickers starting at $start (automatically stops at the end if fewer are left) $currentBatch = array_slice($tickers, $start, $delta); $formattedTickers = implode('"}, {"description": "","proName": "', $currentBatch); echo '<script src="https://s3.tradingview.com/external-embedding/embed-widget-tickers.js"> { "symbols": [{"description": "","proName": "'.$formattedTickers.'"}], "locale": "en" } </script>'; $start += $delta; } ?>
Key Improvements
- Cross-System Line Ending Support: The
auto_detect_line_endingssetting ensures your CSV is read correctly whether it was saved on Windows, Linux, or macOS. - Clean Ticker Filtering:
trim()removes trailing carriage returns/newlines, and we skip empty lines entirely, so your$tickersarray only contains valid symbols. - Reliable Batch Processing: The
whileloop keeps running until every ticker is processed, even if the total number isn't a perfect multiple of$delta. No more missing the final batch of tickers.
Test this with your 197-line CSV: with $delta = 11, you'll get 17 batches of 11 tickers and 1 final batch of 10 tickers, covering all 197 entries without skipping any rows. Adjusting $delta to 15 will also work as expected—no random skipped ranges.
内容的提问来源于stack exchange,提问作者Emre Boyacioglu

