PHP出现Undefined Offset错误,file_put_contents与explode问题求助
Let's break down what's going wrong here and fix it step by step:
1. Why the "+" isn't splitting your data
When you pass the rawData parameter via GET, the + character gets automatically decoded as a space by PHP's $_GET superglobal. That means your explode("+", $rawData) is trying to split on spaces instead of the actual + you intended, leaving you with a single array element instead of two. To fix this, you need to either:
- Encode the
+as%2Bwhen sending the GET request, or - Use
rawurldecode()on$_GET['data']to get the original+character back.
2. Why the Undefined Offset error happens
If $rawData is empty or doesn't contain any +, explode() returns an array with one element. While your loop condition $i < count($lineData) should avoid out-of-bounds access, edge cases (like accidental array modification) or missing GET parameters can still trigger the error. Using a foreach loop instead is safer for array iteration and eliminates this risk entirely.
3. Why your file isn't getting new lines
You're using " " in your string, which isn't a valid newline escape sequence in PHP. You need to use "\n" (Unix-style newlines) or PHP_EOL (auto-adapts to your server's OS) to get actual line breaks in the output file.
Fixed Code
Here's the revised code addressing all these issues:
<?php // Add fallbacks to avoid Undefined Index errors $fileTitle = $_GET['title'] ?? 'default'; // Decode to preserve the original "+" character $rawData = rawurldecode($_GET['data'] ?? ''); // Split the data using the correct "+" delimiter $lineData = explode("+", $rawData); // Use foreach to safely iterate over the array foreach ($lineData as $line) { // Skip empty lines to avoid blank entries if (trim($line) === '') { continue; } $txtFileTitle = $fileTitle . ".txt"; // Use PHP_EOL for proper cross-platform newlines $txtFileLineData = $line . PHP_EOL; $txtFileStatus = file_put_contents($txtFileTitle, $txtFileLineData, FILE_APPEND); if ($txtFileStatus !== false) { echo "SUCCESS: data written to txt file<br>"; } else { echo "FAIL: could not write to txt file<br>"; } } ?>
Key Improvements:
- Added
??null coalescing operators to handle missing GET parameters (prevents Undefined Index errors). - Used
rawurldecode()to ensure the+inrawDatais preserved for splitting. - Switched to a
foreachloop to eliminate Undefined Offset risks entirely. - Used
PHP_EOLto generate proper line breaks across different operating systems. - Added a check to skip empty lines, avoiding blank entries if
rawDataends with+or has empty segments.
Testing with Your Example
If you send title=testing and rawData=5000013,0.00,0.00,50.00,0%2B5006529,0.00,0.00,50.00,0 (note %2B instead of +), the code will split the data correctly and write:
5000013,0.00,0.00,50.00,0 5006529,0.00,0.00,50.00,0
to testing.txt.
内容的提问来源于stack exchange,提问作者iSeeDeadPeople

