note 115655 deleted from function.json-encode by crell

From: Date: Fri, 01 Jul 2022 19:23:43 +0000
Subject: note 115655 deleted from function.json-encode by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218832@lists.php.net to get a copy of this message
Note Submitter: Ray.Paseur often uses Gmail ---- If you're wondering whether a JSON string can be an analog of an XML document, the answer is probably "nope." XML supports attributes, but JSON does not. A JSON string generated by json_encode(), when called on a SimpleXML object, will not have the attributes and no error or exception will issue - the original data will simply be lost. To see this in action: <?php error_reporting(E_ALL); echo '<pre>'; // STARTING FROM XML $xml = <<<EOD <?xml version="1.0" ?> <ingredients> <ingredient> <name>tomatoes</name> <quantity type="cup">4</quantity> </ingredient> <ingredient> <name>salt</name> <quantity type="tablespoon">2</quantity> </ingredient> </ingredients> EOD; // CREATES AN ARRAY OF SimpleXMLElement OBJECTS $obj = SimpleXML_Load_String($xml); var_dump($obj); echo PHP_EOL; // SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS foreach ($obj as $sub) { echo PHP_EOL . (string)$sub->quantity . ' ' . (string)$sub->quantity['type']; } echo PHP_EOL; // USING THE OBJECT, CREATE A JSON STRING $jso = json_encode($obj); echo htmlentities($jso); // 'type' IS LOST echo PHP_EOL;

« previous php.notes (#218832) next »