NodeJsonEncoder::encode

The encode() method of the NodeJsonEncoder class converts a Node object into its JSON string representation. This method ensures that all the Node's structural information, attributes, content, and children are preserved in a format that can be easily transferred or stored.

Description

public NodeJsonEncoder::encode(bool $prettyPrint = false): string

The method serializes the Node object to a JSON string, optionally formatting the output for improved readability.


Parameters

prettyPrint

A boolean flag that determines whether the resulting JSON string should be formatted for readability:

  • true: Outputs the JSON string in a human-readable format with proper indentation and line breaks.
  • false: Outputs the JSON string in a compact, single-line format (default).

Return Value

Returns the JSON string representation of the Node object.

Exceptions

None.


Example

use Ucscode\UssElement\Node\ElementNode;
use Ucscode\UssElement\Serializer\NodeJsonEncoder;

// Example Node
$node = new ElementNode('div');
$node->setAttribute('class', 'container');
$node->setInnerHtml('Hello World');

// Initialize the encoder
$encoder = new NodeJsonEncoder($node);

// Encode with pretty print
$prettyJson = $encoder->encode(true);
JSON Representation
{
    "nodeId": 1,
    "nodeType": 1,
    "nodeName": "DIV",
    "parentId": null,
    "attributes": {
        "class": "container"
    },
    "void": false,
    "visible": true,
    "meta": [],
    "childNodes": [
        {
            "nodeId": 2,
            "nodeType": 3,
            "nodeName": "#TEXT",
            "parentId": 1,
            "attributes": {},
            "void": false,
            "visible": true,
            "meta": {
                "data": "Hello World"
            },
            "childNodes": []
        }
    ]
}
Source Code
If you find this project useful, consider leaving a on GitHub! Thank you!