IntermediateLesson 7 of 16
Strings, Files & JSON – PHP
Processing text (including umlauts), reading/writing files and handling JSON.
PHP has a great many string functions. Since PHP 8 there are finally str_contains, str_starts_with and str_ends_with. For text with accented characters you use the mb_* variants, because the normal functions count bytes.
<?php
var_dump(str_contains("Hello World", "World")); // bool(true)
var_dump(str_starts_with("Hello", "He")); // bool(true)
echo str_replace("a", "A", "Banana"), "\n"; // BAnAnA
print_r(explode(",", "a,b,c"));
echo implode("-", ["x", "y", "z"]), "\n"; // x-y-z
echo sprintf("%05.1f | %s | %'*8d", 3.14159, "ok", 42), "\n"; // 003.1 | ok | ******42
echo number_format(1234567.891, 2, ",", "."), "\n"; // 1.234.567,89
echo strlen("café"), " ", mb_strlen("café"), "\n"; // 5 4
echo mb_strtoupper("café"), "\n"; // CAFÉYou read and write small files with file_get_contents and file_put_contents. For large files, read line by line with fopen/fgets.
<?php
$pfad = __DIR__ . "/notizen.txt";
file_put_contents($pfad, "Line 1\nLine 2\n");
file_put_contents($pfad, "Line 3\n", FILE_APPEND | LOCK_EX);
foreach (file($pfad, FILE_IGNORE_NEW_LINES) as $zeile) {
echo $zeile, "\n";
}
$h = fopen($pfad, "r");
if ($h === false) {
exit("File not readable");
}
while (($zeile = fgets($h)) !== false) {
echo strlen($zeile), " ";
}
fclose($h);JSON is the exchange format of the web. JSON_THROW_ON_ERROR makes broken JSON trigger an exception instead of silently returning null.
<?php
$daten = ["name" => "Ada", "sprachen" => ["PHP", "C"]];
$json = json_encode($daten, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo $json, "\n";
$zurueck = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $zurueck["sprachen"][0], "\n"; // PHPWarningNever build file paths directly from user input (
file_get_contents($_GET["datei"])): with ../../ someone can read arbitrary files (path traversal). Use basename() and an allowlist.