EMZETT.
Login

Kurz: echo file_get_contents(pfad); print_r(file(pfad, FILE_IGNORE_NEW_LINES));

Teil des Kurses PHP

Kapitel 10 von 15 im Kurs PHP (Abschnitt „Praxis“). Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Dateien lesen und schreiben

<?php
$pfad = sys_get_temp_dir() . "/php_demo.txt";
file_put_contents($pfad, "Zeile 1\nZeile 2\nZeile 3\n");
file_put_contents($pfad, "Zeile 4\n", FILE_APPEND);
 
echo file_get_contents($pfad);
print_r(file($pfad, FILE_IGNORE_NEW_LINES));
 
$h = fopen($pfad, "r");                      // zeilenweise: speicherschonend für große Dateien
while (($zeile = fgets($h)) !== false) {
    echo strlen(rtrim($zeile)), " ";
}
fclose($h);
echo "\n";
var_dump(file_exists($pfad), is_file($pfad), is_dir(dirname($pfad)), filesize($pfad));
echo basename("/a/b/datei.txt"), " ", pathinfo("/a/b/datei.tar.gz", PATHINFO_EXTENSION), " ", dirname("/a/b/datei.txt"), "\n";
unlink($pfad);
var_dump(file_exists($pfad));

Ausgabe:

Zeile 1
Zeile 2
Zeile 3
Zeile 4
Array
(
    [0] => Zeile 1
    [1] => Zeile 2
    [2] => Zeile 3
    [3] => Zeile 4
)
7 7 7 7
bool(true)
bool(true)
bool(true)
int(32)
datei.txt gz /a/b
bool(false)

Nutze __DIR__ für Pfade relativ zur aktuellen Datei. Ordner: scandir, glob("*.txt"), mkdir, rmdir.

CSV

<?php
$csv = "name,punkte\nMia,120\nTom,80\n";
$h = fopen("php://memory", "w+");
fwrite($h, $csv);
rewind($h);
$kopf = fgetcsv($h);
while (($z = fgetcsv($h)) !== false) {
    print_r(array_combine($kopf, $z));
}
fclose($h);
 
$aus = fopen("php://output", "w");
fputcsv($aus, ["Name", "Zitat"]);
fputcsv($aus, ["Mia", 'sagt "Hallo", ok']);
fclose($aus);

Ausgabe:

Array
(
    [name] => Mia
    [punkte] => 120
)
Array
(
    [name] => Tom
    [punkte] => 80
)
Name,Zitat
Mia,"sagt ""Hallo"", ok"

JSON

<?php
$daten = ["name" => "Mia", "alter" => 17, "hobbys" => ["Lesen", "Judo"], "aktiv" => true, "adresse" => null];
echo json_encode($daten), "\n";
echo json_encode($daten, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), "\n";
 
$text = '{"name":"Tom","punkte":[1,2,3],"meta":{"ok":true}}';
$obj = json_decode($text);                       // Objekt
$arr = json_decode($text, true);                 // assoziatives Array
echo $obj->name, " ", $arr["punkte"][2], " ", var_export($arr["meta"]["ok"], true), "\n";
 
try {
    json_decode("{kaputt", false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "JSON-Fehler: ", $e->getMessage(), "\n";
}
echo json_encode("Grüße"), json_encode("Grüße", JSON_UNESCAPED_UNICODE), json_encode([1 => "a", 2 => "b"]), json_encode([]), json_encode(new stdClass), "\n";

Ausgabe:

{"name":"Mia","alter":17,"hobbys":["Lesen","Judo"],"aktiv":true,"adresse":null}
{
    "name": "Mia",
    "alter": 17,
    "hobbys": [
        "Lesen",
        "Judo"
    ],
    "aktiv": true,
    "adresse": null
}
Tom 3 true
JSON-Fehler: Syntax error
"Gr\u00fc\u00dfe""Grüße"{"1":"a","2":"b"}[]{}

Verwende JSON_THROW_ON_ERROR, sonst liefert json_decode bei Fehlern still null.

Datum und Zeit

Mit der DateTime-Familie rechnest du sicher mit Daten und Zeitzonen:

<?php
date_default_timezone_set("Europe/Berlin");
 
$d = new DateTimeImmutable("2025-03-15 14:30:00");
echo $d->format("d.m.Y H:i"), " | ", $d->format("l, j. F Y"), " | ", $d->format("W/N/L"), "\n";
echo $d->modify("+1 month")->format("Y-m-d"), " ", $d->modify("last day of this month")->format("Y-m-d"), " ", $d->modify("next monday")->format("D Y-m-d"), "\n";
echo $d->add(new DateInterval("P1Y2M3DT4H"))->format("Y-m-d H:i"), "\n";
 
$a = new DateTimeImmutable("2025-01-01");
$b = new DateTimeImmutable("2025-12-24");
$diff = $a->diff($b);
echo $diff->days, " Tage; ", $diff->m, " Monate, ", $diff->d, " Tage\n";
var_dump($a < $b);
 
$utc = new DateTimeImmutable("2025-06-01 12:00", new DateTimeZone("UTC"));
echo $utc->setTimezone(new DateTimeZone("Asia/Tokyo"))->format("H:i T"), " ", $utc->getTimestamp(), "\n";
 
foreach (new DatePeriod($a, new DateInterval("P1W"), 3) as $tag) echo $tag->format("m-d "), "";
echo "\n";
echo date("Y-m-d", mktime(0, 0, 0, 12, 31, 2024)), " ", date("D", strtotime("2025-07-04")), "\n";

Ausgabe:

15.03.2025 14:30 | Saturday, 15. March 2025 | 11/6/0
2025-04-15 2025-03-31 Mon 2025-03-17
2026-05-18 18:30
357 Tage; 11 Monate, 23 Tage
bool(true)
21:00 JST 1748779200
01-01 01-08 01-15 01-22
2024-12-31 Fri

Bevorzuge die Immutable-Variante: modify und add liefern ein neues Objekt.

Reguläre Ausdrücke (PCRE)

<?php
var_dump(preg_match('/^\d{5}$/', "10115"));
preg_match('/(\d+)-(\d+)/', "Tel 030-1234", $m);
print_r($m);
preg_match('/(?<jahr>\d{4})-(?<monat>\d{2})/', "Datum 2025-03-15", $m);
echo $m['jahr'], "/", $m['monat'], "\n";
echo preg_replace('/\s+/', ' ', "viel    Platz \n hier"), "|", preg_replace('/(\w+)@(\w+)/', '$2 at $1', "mia@example"), "\n";
preg_match_all('/\b[A-Z]\w+/', "Mia und Tom aus Berlin", $alle);
print_r($alle[0]);
print_r(preg_split('/[,;]\s*/', "a, b;c,  d"));
echo preg_replace_callback('/\d+/', fn($m) => $m[0] * 2, "3 Äpfel, 10 Birnen"), "\n";
var_dump(filter_var("mia@example.com", FILTER_VALIDATE_EMAIL), filter_var("kein email", FILTER_VALIDATE_EMAIL), filter_var("42", FILTER_VALIDATE_INT), filter_var("abc", FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE));

Ausgabe:

int(1)
Array
(
    [0] => 030-1234
    [1] => 030
    [2] => 1234
)
2025/03
viel Platz hier|example at mia
Array
(
    [0] => Mia
    [1] => Tom
    [2] => Berlin
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
6 Äpfel, 20 Birnen
string(15) "mia@example.com"
bool(false)
int(42)
NULL

Merke

  • file_get_contents, file_put_contents, fopen/fgets, file
  • fgetcsv/fputcsv für CSV; json_encode/json_decode mit JSON_THROW_ON_ERROR
  • DateTimeImmutable, DateInterval, DateTimeZone für Zeitrechnung
  • preg_match, preg_match_all, preg_replace, preg_split für reguläre Ausdrücke
  • filter_var validiert E-Mails, Zahlen, URLs

Übungsaufgabe

Lies eine CSV mit Namen und Punkten, sortiere nach Punkten und schreibe das Ergebnis als JSON-Datei.

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Fehlerbehandlung und Exceptions

Weiter: Datenbanken mit PDO

Alle Kapitel: PHP im Überblick