note 115655 added to function.json-encode
| From: | Ray.PaseuroftenusesGmail | Date: | Tue, 02 Sep 2014 18:15:46 +0000 |
| Subject: | note 115655 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-200360@lists.php.net to get a copy of this message | ||
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;
----
Server IP: 64.71.164.2
Probable Submitter: 98.169.66.145
----
Manual Page -- http://php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/115655
Del: integrated -- https://master.php.net/note/delete/115655/integrated
Del: useless -- https://master.php.net/note/delete/115655/useless
Del: bad code -- https://master.php.net/note/delete/115655/bad+code
Del: spam -- https://master.php.net/note/delete/115655/spam
Del: non-english -- https://master.php.net/note/delete/115655/non-english
Del: in docs -- https://master.php.net/note/delete/115655/in+docs
Del: other reasons-- https://master.php.net/note/delete/115655
Reject -- https://master.php.net/note/reject/115655
Search -- https://master.php.net/manage/user-notes.php