SyntaxStudy
Sign Up
PHP JSON and XML Best Practices in PHP
PHP Intermediate 4 min read

JSON and XML Best Practices in PHP

JSON/XML Best Practices

Always validate and sanitize incoming JSON/XML, use JSON_THROW_ON_ERROR, handle encoding issues with proper charset settings, and never trust externally provided XML (XXE attacks).

Example
<?php
// Prevent XXE (XML External Entity) attacks
libxml_disable_entity_loader(true); // PHP < 8.0
// PHP 8.0+ disabled entity loading by default

// Always validate incoming JSON
function parseJsonInput(): array {
    $raw = file_get_contents("php://input");
    try {
        return json_decode($raw, true, 512, JSON_THROW_ON_ERROR) ?? [];
    } catch (\JsonException $e) {
        throw new InvalidArgumentException("Invalid JSON body: " . $e->getMessage());
    }
}

// Sanitize before using in output
$safe = htmlspecialchars($data["name"], ENT_QUOTES, "UTF-8");
Pro Tip

XML External Entity (XXE) attacks exploit XML parsers that resolve external entities — always disable entity loading for untrusted XML.