

Taken the problems that were highlighted in the first two parts, a routine seems useful that returns an array or object structure that can represent text including CDATA, attributes and children at once. This is done by changing the public function jsonSerialize(). So now it’s up to change this standard implementation. When executed, this example shows that the JSON yet still is the same as if without that parameter: In this example note that by creating the SimpleXMLElement with the simplexml_load_string() function, the new sub-type is used: JsonXMLElement. $xml = simplexml_load_string($buffer, 'JsonXMLElement') Įcho json_encode($xml, JSON_PRETTY_PRINT), "\n" But before changing these characteristics, first a usage example of such an JSON XML encoder:

#Php json decode attributes code#
This is really only boilerplate code because having such an implementation will encode the JSON exactly as it had been done before. * mixed data which can be serialized by json_encode. * Specify data which should be serialized to JSON In this example, the standard array casting is used:Ĭlass JsonXMLElement extends SimpleXMLElement implements JsonSerializable
#Php json decode attributes how to#
The following boilerplate code shows how to implement such a serialization. This allows to create an own JSON encoding easily by extending from SimpleXMLElement and implementing the interface as I will show now. Just anything which json_encode() would normally accept. Instead of the standard array cast, a more tailored array or object – even a string or number – can be returned. Luckily since PHP 5.4 the JsonSerializable interface allows to interfere exactly at that point. This is because internally (see lxr json.c) json_encode() does this cast and then builds the JSON object output based on that structure. However those worked by affecting the XML document instead of affecting the JSON serialization.īy default what json_encode() contains as data and structure is exactly following the rules of casting a SimpleXMLElement to an array. The previous two parts ( Part I Part II) did outline PHP’s standard behaviour when JSON encoding a SimpleXMLElement with json_encode().Īs outlined this does not always fits the encoding needs and for some potential problems some workarounds have been showed.
