@toJson & @fromJson - JSON Conversion

The @toJson and @fromJson directives in Ahmed PHP Template Engine allow you to convert data to and from JSON format.

Syntax

@toJson(data)
@fromJson(jsonString)
  • data: The PHP array or object to be converted into a JSON string.

  • jsonString: The JSON string to be converted into a PHP array.

Description

  • @toJson converts an array or object into a JSON-encoded string.

  • @fromJson converts a JSON string back into a PHP array.

  • Useful for handling API responses, data storage, and dynamic content manipulation.

Example

Convert PHP Array to JSON

@var(user, {"name": "Ahmed", "age": 25})
<p>@toJson(user)</p>

Expected Output:

{"name": "Ahmed", "age": 25}

Convert JSON String to PHP Array

Expected Output:

Notes

  • @toJson ensures proper JSON formatting for data exchange.

  • @fromJson automatically decodes valid JSON into an array.

  • Ensure the JSON string is properly formatted to avoid errors.

Last updated