Skip to content
Tutorials Center
My learning

Topics

Lesson 144 of 147 ยท Practice and Review

PHP JSON and File System Programs: 8 Practical Examples

8 PHP programs with output - JSON to CSV, XML to JSON, arrays to JavaScript, receiving a JSON POST, creating folders, deleting files, listing a tree and logging errors to a file.

Data conversion and file chores fill a large part of everyday PHP work: a partner sends JSON and your accountant wants a CSV; an old system exports XML and your front end wants JSON; you need a scratch folder that may not exist yet, or a clean-up script that deletes yesterday's files. This page has eight such programs. Each one is complete, uses only the standard library, and runs on the PHP 8.5 runner. Where the real input would come from a web request or a real project folder, the program builds its own sample data in a temporary directory so you can run it safely.

Background lessons: JSON, CSV Files, XML, Files and Directories and File Handling. Two safety habits apply to every program below: use JSON_THROW_ON_ERROR so bad JSON fails loudly, and build file paths from a trusted base folder, never from raw user input (see Secure Coding).

Converting data

1. JSON to CSV

Decode the JSON into an array of records, write the header from the keys of the first record and use fputcsv() for the rows, so commas and quotes inside values are escaped correctly. The sample writes to php://output, i.e. the screen; swap in a file handle to save it.

PHP 1. JSON to CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

fputcsv() quotes the value New York, NY and doubles the quotes inside the note. Passing the $escape argument explicitly ('\\' or '') avoids a deprecation warning in PHP 8.4 and later.

2. XML to JSON

simplexml_load_string() parses XML and a round trip through json_encode() and json_decode() flattens it into arrays. Attributes land under an @attributes key. This quick trick loses the order of mixed content, but it is perfect for configuration-like documents.

PHP 2. XML to JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the trap in the comment: with exactly one <book> the decoder gives you an object, not a one-item list. For exact control use a DOMDocument and XPath instead.

3. Pass an array to JavaScript

json_encode() produces valid JavaScript literals. To embed JSON inside an HTML <script> tag safely, add the JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS and JSON_HEX_QUOT flags, so that a value containing </script> cannot break out of the script.

PHP 3. Array to JavaScript

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The dangerous </script> appears as </script>, so it is data and not markup. This is the escaping rule from XSS and Output Escaping applied to the JavaScript context.

4. Receive a JSON POST request

A request with Content-Type: application/json does not fill $_POST; you read the raw body from php://input and decode it. The function below takes the body as a string so you can test it here; on a real server you would call it with file_get_contents('php://input').

PHP 4. Handle a JSON POST body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The status codes tell the client what went wrong: 415 for the wrong media type, 400 for broken JSON and 422 for valid JSON with unacceptable content. See REST APIs.

File system chores

5. Create a folder only if it does not exist

mkdir($path, 0775, true) creates the folder and any missing parents. Combine it with is_dir() so a second run does not warn, and check the return value, because creation can fail because of permissions. A race between two requests can still make mkdir() fail after your check, so re-test is_dir() when it returns false.

PHP 5. Ensure a folder exists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

6. Delete all files in a folder

glob() lists the files, is_file() skips sub-folders and unlink() deletes. Be very careful with the folder you pass: log first, and refuse to run when the path is empty or a root folder.

PHP 6. Empty a folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

glob('*') skips hidden files whose names start with a dot. Use scandir() if you need them as well.

7. List all files recursively

RecursiveDirectoryIterator wrapped in RecursiveIteratorIterator walks any depth without writing your own recursion. SKIP_DOTS hides . and ...

PHP 7. Recursive listing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Directory order is not guaranteed, so sort the results when you need stable output. More on iterators is in Iterators and SPL.

8. Log errors to a file

error_log($message, 3, $file) appends to a file you choose. Better still, set PHP to log errors to a file for you and keep them off the screen in production: display_errors=0, log_errors=1 and error_log=/path/app.log. Here a custom handler writes warnings in a tidy format.

PHP 8. Error log file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In real code log with a logger that adds timestamps and levels for you, as in Logging with PSR-3, and never print raw errors to visitors (Errors).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does $_POST stay empty for a request with Content-Type application/json?

    Only application/x-www-form-urlencoded and multipart/form-data are parsed into $_POST. For JSON, decode php://input yourself.
  2. 2. What does the JSON_HEX_TAG flag help prevent when embedding JSON in a script tag?

    JSON_HEX_TAG writes < and > as < and >, so the browser cannot see a closing tag inside data.
  3. 3. What does mkdir($path, 0775, true) do that mkdir($path) does not?

    The third argument turns on recursive creation, so "a/b/c" works even if "a" and "a/b" do not exist.
  4. 4. Which HTTP status best describes valid JSON whose content fails validation?

    422 Unprocessable Content means the request was well formed but its content is not acceptable. 400 is for malformed requests.

Summary

  • Decode with JSON_THROW_ON_ERROR; write CSV with fputcsv() so quoting is correct.
  • XML can be turned into JSON via SimpleXML, but one-item lists become objects, so normalize them.
  • Embed JSON in HTML scripts with the JSON_HEX_* flags.
  • JSON request bodies live in php://input, not $_POST; answer 415, 400 or 422 for the three kinds of failure.
  • mkdir(..., true) plus is_dir() gives idempotent folder creation; glob() with is_file() and unlink() deletes files only.
  • RecursiveDirectoryIterator walks a tree; error_log($msg, 3, $file) appends to a log.

Next: Practical PHP Snippets