How can PHP developers ensure data integrity and consistency when dealing with data from external sources like JSON?
To ensure data integrity and consistency when dealing with data from external sources like JSON, PHP developers can validate the incoming JSON data against a predefined schema. This can help ensure that the data structure is as expected, preventing any unexpected errors or inconsistencies in the data.
// Example code snippet to validate JSON data against a schema using JSON Schema
$jsonData = '{"name": "John Doe", "age": 30}';
$schema = '{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}';
$validator = new JsonSchema\Validator;
$validator->validate(json_decode($jsonData), json_decode($schema));
if ($validator->isValid()) {
echo "JSON data is valid!";
} else {
echo "JSON data is invalid!";
}