JSON and CSV from the same page
A page's PHP already produces its data, so the same page can answer with that data instead of rendering its template. The PHP names what may leave the server in $padExpose - nothing else ever does, and an engine variable never does:
|
PHP fragments/data_answers_1.php |
HTML fragments/data_answers_1.pad |
Result |
|---|---|---|
|
|
Total: 19.5 |
Asked with &padFormat=json - or by a client sending Accept: application/json - that page answers the named variables as one JSON object. &padFormat=csv, or Accept: text/csv, answers the first list among them as a table with a header row. The template does not run for either:
|
PHP fragments/data_answers_2.php |
HTML fragments/data_answers_2.pad |
Result |
|---|---|---|
|
|
{
"orders": [
{
"id": 1,
"customer": "Ann",
"amount": 12.5
},
{
"id": 2,
"customer": "Bob",
"amount": 7
}
],
"total": 19.5
}
id,customer,amount 1,Ann,12.5 2,Bob,7 |
- A page that exposes nothing renders its HTML as always. Asked outright with
padFormat=, it answers 406 Not Acceptable - as does a format that does not exist, or CSV from a page with no list. -
$padOutputType = 'json'(or'csv') in_config/config.phpmakes every page of an application answer its data;{output 'json'}does it from a template. - A script or a React component fetches from the ordinary page:
fetch('?orders&padFormat=json').