CSV to PHP Array Converter
Turn a CSV export into a PHP array in short [] syntax, ready to paste into a seeder, a config file or a test fixture. Numbers, booleans and nulls are written unquoted, so you do not have to fix types afterwards. Only values that look like JSON numbers are converted, so a ZIP code like 00501 stays the string "00501".
1 CSV to PHP Array example
Input CSV
2
3
id,name,role,active
1,John Doe,Admin,true
2,Jane Smith,User,false PHP Output
2
3
4
5
6
7
8
9
10
11
12
13
14
[
[
'id' => 1,
'name' => 'John Doe',
'role' => 'Admin',
'active' => true
],
[
'id' => 2,
'name' => 'Jane Smith',
'role' => 'User',
'active' => false
]
] 2 Where CSV to PHP Array output fits
Seeders and fixtures
Convert a spreadsheet export once and paste the array into a database seeder or a PHPUnit data provider.
Config files
Commit the array when someone else maintains the list in a spreadsheet. Re-export and convert when it changes, and your code loads it with a plain require.
Workflow
Turning CSV records into PHP arrays
- 01 Paste CSV into the left editor, or bring it in with Upload CSV or Load URL.
- 02 Pick the delimiter: comma, semicolon, tab or pipe. Select Custom and type a character if your file uses something else.
- 03 The PHP array on the right updates as you type. Each row becomes an associative array keyed by the header names, with numbers and booleans typed rather than left as strings.
- 04 Click Dummy Data at any time to load a sample and see the output format.
- 05 Click Copy PHP and paste the array into a file after <?php with a return or an assignment.
In code
How to convert CSV to a PHP array in PHP and Python
PHP
php<?php
$csv = "sku,price,in_stock\nA-100,9.99,true\nB-200,15,false\n";
$handle = fopen('php://memory', 'r+');
fwrite($handle, $csv);
rewind($handle);
$headers = fgetcsv($handle, null, ',', '"', '\\');
$rows = [];
while (($line = fgetcsv($handle, null, ',', '"', '\\')) !== false) {
$rows[] = array_combine($headers, $line);
}
// Every value is a string; cast the columns you need
foreach ($rows as &$row) {
$row['price'] = (float) $row['price'];
$row['in_stock'] = filter_var($row['in_stock'], FILTER_VALIDATE_BOOLEAN);
}
file_put_contents('products.php', "<?php\n\nreturn " . var_export($rows, true) . ";\n");
echo file_get_contents('products.php'); var_export() writes long array() syntax with numeric indexes. Pass the delimiter as the third argument of fgetcsv() for semicolon files.
Python
pythonimport csv, io
text = "sku,price,in_stock\nA-100,9.99,true\nB-200,15,false\n"
def php(value):
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return str(value)
return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"
def cast(v):
if v.lower() in ("true", "false"):
return v.lower() == "true"
try:
return int(v) if v.isdigit() else float(v)
except ValueError:
return v
rows = csv.DictReader(io.StringIO(text))
lines = []
for row in rows:
pairs = ", ".join(php(k) + " => " + php(cast(v)) for k, v in row.items())
lines.append(" [" + pairs + "],")
print("<?php\n\nreturn [\n" + "\n".join(lines) + "\n];") Useful as a build step when the source of truth is a spreadsheet and the PHP project should not be parsing CSV at runtime.
Troubleshooting
Multiline fields and escaping errors
- array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements
- A row has more or fewer fields than the header, often a trailing blank line or an unquoted comma inside a value. Skip [null] rows and pad short rows with array_pad().
- Warning: Undefined array key "name"
- The header contains a byte order mark or trailing whitespace, so the real key is "\xEF\xBB\xBFname" or "name ". Trim the header cells and strip the BOM before using them as keys.
- Every value is a string, so 10 > 9 comparisons behave oddly
- fgetcsv() returns strings only. Cast numeric columns with (int) or (float), and use filter_var($v, FILTER_VALIDATE_BOOLEAN) for true/false columns.
- Deprecated: fgetcsv(): the $escape parameter must be provided
- PHP 8.4 deprecates the default escape character. Pass '\\' explicitly, or an empty string to disable escaping, which is what RFC 4180 expects.
Notes
Short array syntax vs var_export output
PHP's CSV functions predate RFC 4180. They recognize a backslash escape character on top of the standard doubled quotes, so a field containing \" reads differently from what Excel would have written. Pass an empty string as the escape argument to get standard behavior; PHP 8.4's deprecation warning pushes code in that direction.
Converting also pays off at runtime because of OPcache. A file that returns a static array is compiled once and cached, so for a few thousand rows it loads faster than parsing the CSV on every request.
Docs
RFC 4180 and PHP array references
Answers
CSV to PHP questions
Does the output use the header row as keys?
Yes. Each row becomes an associative array keyed by the header names, so the result is a list of rows ready for a foreach loop.
Which PHP versions can use the output?
The short array syntax [] needs PHP 5.4 or newer, so every supported PHP version accepts it, PHP 8.x included.
Can I change the delimiter?
Yes. Choose comma, semicolon, tab or pipe, or pick Custom and type your own delimiter. The output updates as soon as you change it.
Why convert instead of using fgetcsv()?
Use fgetcsv() to read files at runtime. This tool is for static data you want to commit as code: seeders, lookup tables, test fixtures or config arrays.
Are quotes and special characters escaped?
Yes. Strings are single-quoted, and any single quote or backslash inside them is escaped, so the output is valid PHP.