CSV text can be read from a file and parsed into selected scalar fields.

parsed fields Parse only the fields needed for the lesson so public replay stays scalar.

CSV Fields

qty
csv_fields.php
Replay: real traced execution (multi-file project)
<?php
$qty = 3;
$file = "php_csv_file.txt";

file_put_contents($file, "item,qty\npen," . $qty . "\n");
$row = explode("\n", trim(file_get_contents($file)))[1];
$item = str_getcsv($row)[0];
$count = (int) str_getcsv($row)[1];
unlink($file);

echo "item=" . $item . "\n";
echo "count=" . $count . "\n";
<?php
$qty = 1;
$file = "php_csv_file.txt";

file_put_contents($file, "item,qty\npen," . $qty . "\n");
$row = explode("\n", trim(file_get_contents($file)))[1];
$item = str_getcsv($row)[0];
$count = (int) str_getcsv($row)[1];
unlink($file);

echo "item=" . $item . "\n";
echo "count=" . $count . "\n";
<?php
$qty = 8;
$file = "php_csv_file.txt";

file_put_contents($file, "item,qty\npen," . $qty . "\n");
$row = explode("\n", trim(file_get_contents($file)))[1];
$item = str_getcsv($row)[0];
$count = (int) str_getcsv($row)[1];
unlink($file);

echo "item=" . $item . "\n";
echo "count=" . $count . "\n";
  1. $qty ← 3, $file ← php_csv_file.txt, $row ← pen,3, $item ← pen

    1<?php2$qty→ 3 = 3; //@qty=1, 83$file→ php_csv_file.txt = "php_csv_file.txt";45file_put_contents($filephp_csv_file.txt, "item,qty\npen," . $qty3 . "\n");6$row→ pen,3 = explode("\n", trim(file_get_contents($file)))[1]pen,3;7$item→ pen = str_getcsv($row)[0]pen;8$count→ 3 = (int) str_getcsv($row)[1]3;9unlink($filephp_csv_file.txt);1011echo "item=" . $itempen . "\n";12echo "count=" . $count3 . "\n";
    outputitem=pen
    count=3
  1. $qty ← 1, $file ← php_csv_file.txt, $row ← pen,1, $item ← pen

    1<?php2$qty→ 1 = 1;3$file→ php_csv_file.txt = "php_csv_file.txt";45file_put_contents($filephp_csv_file.txt, "item,qty\npen," . $qty1 . "\n");6$row→ pen,1 = explode("\n", trim(file_get_contents($file)))[1]pen,1;7$item→ pen = str_getcsv($row)[0]pen;8$count→ 1 = (int) str_getcsv($row)[1]1;9unlink($filephp_csv_file.txt);1011echo "item=" . $itempen . "\n";12echo "count=" . $count1 . "\n";
    outputitem=pen
    count=1
  1. $qty ← 8, $file ← php_csv_file.txt, $row ← pen,8, $item ← pen

    1<?php2$qty→ 8 = 8;3$file→ php_csv_file.txt = "php_csv_file.txt";45file_put_contents($filephp_csv_file.txt, "item,qty\npen," . $qty8 . "\n");6$row→ pen,8 = explode("\n", trim(file_get_contents($file)))[1]pen,8;7$item→ pen = str_getcsv($row)[0]pen;8$count→ 8 = (int) str_getcsv($row)[1]8;9unlink($filephp_csv_file.txt);1011echo "item=" . $itempen . "\n";12echo "count=" . $count8 . "\n";
    outputitem=pen
    count=8