PHP Doku:: Dekodiert eine JSON-Zeichenkette - function.json-decode.html

Verlauf / Chronik / History: (7) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige GrunderweiterungenJavaScript-Objekt-NotationJSON-Funktionenjson_decode

Ein Service von Reinhard Neidl - Webprogrammierung.

JSON-Funktionen

<<JSON-Funktionen

json_encode>>

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decodeDekodiert eine JSON-Zeichenkette

Beschreibung

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 ]] )

Konvertiert eine JSON-kodierte Zeichenkette in eine PHP-Variable.

Parameter-Liste

json

Der zu dekodierende json-String.

assoc

Wenn TRUE, werden zurückgegebene Objekte in assoziative Arrays konvertiert.

depth

Benutzerspezifische Verschachtelungstiefe.

Rückgabewerte

Gibt den Wert von json im passenden PHP-Typ zurück. Die Werte true, false und null werden (unabhängig von Groß-/Kleinschreibung) entsprechend als TRUE, FALSE und NULL zurückgegeben. NULL wird zurückgegeben, wenn der Parameter json nicht dekodiert werden kann oder wenn die dekodierten Daten tiefer verschachtelt sind, als es der Parameter für Verschachtelungstiefe erlaubt.

Beispiele

Beispiel #1 json_decode()-Beispiele

<?php
$json 
'{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($jsontrue));

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Beispiel #2 Ein weiteres Beispiel

<?php

$json 
'{"foo-bar": 12345}';

$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345

?>

Beispiel #3 Häufige Fehler bei der Verwendung von json_decode()

<?php

// die folgenden Zeichenketten sind gültiges JavaScript aber kein gültiges JSON

// der Name und der Wert müssen in doppelten Anführungszeichen eingeschlossen werden
// einfache Anführungszeichen sind ungültig
$bad_json "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// der Name muss in doppelten Anführungszeichen eingeschlossen werden
$bad_json '{ bar: "baz" }';
json_decode($bad_json); // null

// nachfolgende Kommata sind nicht erlaubt
$bad_json '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Beispiel #4 Fehler bei der Verwendung von depth

<?php
// Daten kodieren
$json json_encode(
    array(
        
=> array(
            
'englisch' => array(
                
'One',
                
'January'
            
),
            
'französisch' => array(
                
'Une',
                
'Janvier'
            
)
        )
    )
);

// Errordefinitionen
$json_errors = array(
    
JSON_ERROR_NONE => 'Es ist kein Fehler aufgetreten',
    
JSON_ERROR_DEPTH => 'Die maximale Stacktiefe wurde erreicht',
    
JSON_ERROR_CTRL_CHAR => 'Steuerzeichenfehler, möglicherweise fehlerhaft kodiert',
    
JSON_ERROR_SYNTAX => 'Syntaxfehler',
);

// Zeige die Fehler für unterschiedliche Verschachtelungstiefen
foreach(range(43, -1) as $depth) {
    
var_dump(json_decode($jsontrue$depth));
    echo 
'Letzter Fehler : '$json_errors[json_last_error()], PHP_EOLPHP_EOL;
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Letzter Fehler : Es ist kein Fehler aufgetreten

NULL
Letzter Fehler : Die maximale Stacktiefe wurde erreicht

Anmerkungen

Hinweis:

Die JSON-Spezifikation ist nicht JavaScript, aber ein Subset davon.

Hinweis:

Tritt ein Dekodierungsfehler auf, kann json_last_error() verwendet werden, um die exakte Natur des Fehlers zu ermitteln.

Changelog

Version Beschreibung
5.3.0 Der optionale Parameter depth wurde hinzugefügt. Die Standardrekursionstiefe wurde von 128 auf 512 heraufgesetzt.
5.2.3 Die Verschachtelungsgrenze wurde von 20 auf 128 angehoben.

Siehe auch


40 BenutzerBeiträge:
- Beiträge aktualisieren...
contacto at hardcode dot com dot ar
25.11.2010 22:53
If you have a json encoded array that contains non UTF8 chars, this function will do the trick:

<?php
$array
= json_decode(safeJSON_chars($iso_8859_1_data));

function
safeJSON_chars($data) {

   
$aux = str_split($data);

    foreach(
$aux as $a) {

       
$a1 = urlencode($a);

       
$aa = explode("%", $a1);

        foreach(
$aa as $v) {

            if(
$v!="") {

                if(
hexdec($v)>127) {

               
$data = str_replace($a,"&#".hexdec($v).";",$data);

                }

            }

        }

    }

    return
$data;

}
?>

Of course it works if you want to show this inside a HTML page, so entities will be converted.
Hope this helps you as much as it helped me.
Anonymous
3.11.2010 22:22
to deal with escaped dbl-quotes this is required:
if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
revision is as follows:

<?php
if ( !function_exists('json_decode') ){
function
json_decode($json)
{
   
$comment = false;
   
$out = '$x=';
 
    for (
$i=0; $i<strlen($json); $i++)
    {
        if (!
$comment)
        {
            if ((
$json[$i] == '{') || ($json[$i] == '['))       $out .= ' array(';
            else if ((
$json[$i] == '}') || ($json[$i] == ']'))   $out .= ')';
            else if (
$json[$i] == ':')    $out .= '=>';
            else                        
$out .= $json[$i];         
        }
        else
$out .= $json[$i];
        if (
$json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
    }
    eval(
$out . ';');
    return
$x;
}
}
?>
Jestep
8.09.2010 22:26
I had a JSON string with multiple commas in it without any quotes, which was causing the json_decode to return false.

Once the double quotes were added, everything worked out fine.

A quick:

while(strpos($contents, ',,') !== false) {
    $contents = str_replace(',,', ',"",', $contents);
}

solved the problem, and the function worked correctly. If you have tried everything and are still a FALSE return, I suggest trying the JSON validator in another post.
T erkif
11.08.2010 0:03
it seems, that some of the people are not aware, that if you are using json_decode to decode a string it HAS to be a propper json string:

<?php
var_dump
(json_encode('Hello'));

var_dump(json_decode('Hello'));  // wrong
var_dump(json_decode("Hello")); // wrong
var_dump(json_decode('"Hello"')); // correct
var_dump(json_decode("'Hello'")); // wrong

result:

string(7) ""Hello""
NULL
NULL
string
(5) "Hello"
NULL
zgardner at allofe dot com
19.07.2010 19:23
There seems to be a difference in the way json_decode works between 5.2.9 and 5.2.6. Trying to run json_decode on a URL in 5.2.6 will return the URL, but in 5.2.9 it will return NULL.

5.2.6
var_dump(json_decode("http://www.php.net")); // Displays string(18) "http://www.php.net"

5.2.9
var_dump(json_decode("http://www.php.net")); // Displays NULL

The servers I tested it on both had json version 1.2.1.
steveo at crecon dot com
23.06.2010 20:11
I was getting an array like:
  Array
  (
      [COLUMNS] => Array
          (
              [0] => ID
              [1] => FIRST
              [2] => LAST
           )
      [DATA] => Array
          (
              [0] => Array
                    (
                          [0] => 10
                          [1] => Mary
                          [2] => Smith
                     )
               [1] => Array
                     (
                          [0] => 11
                          [1] => Joe
                          [2] => Black
                     )
               [2] => Array
                     (
                          [0] => 12
                          [1] => Tom
                          [2] => Green
                     )
               [3] => Array
       . . .

With lots more columns and data from a json_decode call to a Cold Fusion .cfc which returned a database query. This is easy to turn into a nice associative array with the following code:

<?php
 
foreach ($results['DATA'] as $rowcount => $row){
     foreach (
$row as $colcount => $col){
      
$lines[$rowcount][$results['COLUMNS'][$colcount]]=$col;
     }
  }
?>

to get:
Array
(
  [0] => Array
       (
          [ID]      => 10
          [FIRST] => Mary
          [LAST]  => Smith
        )
  [1] => Array
       (
         [ID]       => 11
         [FIRST]  => Joe
         [LAST]   => Black
       )
. . . etc.

I hope this helps someone.
majca J
6.06.2010 2:42
Noted in a comment below is that this function will return NULL when given a simple string.

This is new behavior - see the result in PHP 5.2.4 :
php > var_dump(json_decode('this is a simple string'));
string(23) "this is a simple string"

in PHP 5.3.2 :
php > var_dump(json_decode('this is a simple string'));
NULL

I had several functions that relied on checking the value of a purported JSON string if it didn't decode into an object/array. If you do too, be sure to be aware of this when upgrading to PHP 5.3.
phpuser
20.05.2010 12:52
If you keep having problems, try removing "problematic" characters from the json string:

$obj = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string);
NemoStein
19.05.2010 19:43
Pass you URL encoded ( urlencode($json) ), then decode it ( urldecode($_GET['json']) )...

Should do the trick...
Mitchell Simoens
6.05.2010 1:27
In my case, I was passing simple JSON in the URL...

eg myfile.php?test=["one", "two", "three"]

but I kept getting NULL no matter what I tried. I did a simple echo of $_REQUEST["test"] and noticed that the browser added the "\" to the double-quotes. I had to prepare the data first then do the decode:

<?php
$data
= str_replace("\\", "", $_REQUEST["test"]);
$results = json_decode($data);
?>

This produced what was expected
php dot net at spam dot lublink dot net
2.04.2010 16:25
If the JSON is coming from javascript watch out for undefined variables :

Javascript ( using dojo ) returns this to me sometimes :

{ "index" : [undefined] }

When I pass this to json_decode, it returns null. Make sure that you check all your javascript variables properly because this can break whatever it is you are doing.
CraigHarris at gmail dot com
19.02.2010 21:55
Be aware that json_decode() will return null if you pass it a JSON encoded string.

<?php echo json_encode('Some String'); ?>
"Some String"
<?php echo json_decode(json_encode('Some String')); ?>
NULL
<?php // expected output ?>
Some String
php at hm2k.org
12.02.2010 1:45
If var_dump produces NULL, you may be experiencing JSONP aka JSON with padding, here's a quick fix...

<?php

//remove padding
$body=preg_replace('/.+?({.+}).+/','$1',$body);

// now, process the JSON string
$result = json_decode($body);

var_dump($result);
?>
nix
29.01.2010 12:39
Be aware, when decoding JSON strings, where an empty string is a key, this library replaces the empty string with "_empty_".

So the following code gives an unexpected result:
<?php
var_dump
(json_decode('{"":"arbitrary"}'));
?>

The result is as follows:
object(stdClass)#1 (1) {
  ["_empty_"]=>
  string(6) "arbitrary"
}

Any subsequent key named "_empty_" (or "" [the empty string] again) will overwrite the value.
yohan dot widyakencana at kreators dot com
29.01.2010 9:37
When in php 5.2.3, I found that json_decode 4000000000 float value into integer value resulting int(-294967296) from var_dump function

When in php 5.3.x, php correctly returning float(4000000000)

thank you for people creating & upgrading php

Yohan W.
colin.mollenhour.com
21.01.2010 19:51
For those of you wanting json_decode to be a little more lenient (more like Javascript), here is a wrapper:

<?php
function json_decode_nice($json, $assoc = FALSE){
   
$json = str_replace(array("\n","\r"),"",$json);
   
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    return
json_decode($json,$assoc);
}
?>

Some examples of accepted syntax:

<?php
$json
= '{a:{b:"c",d:["e","f",0]}}';
$json =
'{
   a : {
      b : "c",
      "d.e.f": "g"
   }
}'
;
?>

If your content needs to have newlines, do this:

<?php
$string
= "This
Text
Has
Newlines"
;
$json = '{withnewlines:'.json_encode($string).'}';
?>

Note: This does not fix trailing commas or single quotes.
wesgeek at gmx dot com
24.12.2009 19:22
If you are having issues with magic_quotes_gpc being turned on and can't disable it use json_decode(stripslashes($json)).
benny at zami-nospam-nga dot com
16.10.2009 11:35
I pulled my hair off for hours trying to get rid of strange backslashes in my incoming JSON-data in POST-pool, making it impossible to decode the incoming JSON-data.

For those of you facing the same problem:

just make sure you disable 'magic_quotes_gpc' in your php.ini and the incoming data will not be pseudo-escaped anymore. Now your incoming JSON-data should just be decoded fine.

Maybe this will help.
simonKenyonShepard at trisis dot co dot uk
14.10.2009 20:23
BEWARE!

json_decode will NOT WORK if there ARE LINE BREAKS in the JSON!

Use str_replace to get rid of them.
confusioner at msn dot com
18.07.2009 2:33
if you can not decode unicode characters with json_decode, use addslashes() while using json_encode. The problem comes from unicode chars starting with \ such as \u30d7

$json_data = addslashes(json_encode($unicode_string_or_array));
Nick Telford
25.06.2009 13:06
In PHP <= 5.1.6 trying to decode an integer value that's > PHP_INT_MAX will result in an intger of PHP_INT_MAX.

In PHP 5.2+ decoding an integer > PHP_INT_MAX will cause a conversion to a float.

Neither behaviour is perfect, capping at PHP_INT_MAX is marginally worse, but the float conversion loses precision.

If you expect to deal with large numbers at all, let alone in JSON, ensure you're using a 64-bit system.
premiersullivan at gmail dot com
22.06.2009 1:14
This function will remove trailing commas and encode in utf8, which might solve many people's problems. Someone might want to expand it to also change single quotes to double quotes, and fix other kinds of json breakage.

<?php
   
function mjson_decode($json)
    {
        return
json_decode(removeTrailingCommas(utf8_encode($json)));
    }
   
    function
removeTrailingCommas($json)
    {
       
$json=preg_replace('/,\s*([\]}])/m', '$1', $json);
        return
$json;
    }
?>
www at walidator dot info
30.05.2009 16:16
Here's a small function to decode JSON. It might not work on all data, but it works fine on something like this:

$json_data = '{"response": {
    "Text":"Hello there"
 },
 "Details": null, "Status": 200}
 ';

===== CUt HERE :) =====

<?php
if ( !function_exists('json_decode') ){
function
json_decode($json)

   
// Author: walidator.info 2009
   
$comment = false;
   
$out = '$x=';
   
    for (
$i=0; $i<strlen($json); $i++)
    {
        if (!
$comment)
        {
            if (
$json[$i] == '{')        $out .= ' array(';
            else if (
$json[$i] == '}')    $out .= ')';
            else if (
$json[$i] == ':')    $out .= '=>';
            else                        
$out .= $json[$i];           
        }
        else
$out .= $json[$i];
        if (
$json[$i] == '"')    $comment = !$comment;
    }
    eval(
$out . ';');
    return
$x;

}
?>
Gravis
10.05.2009 4:38
with two lines you can convert your string from JavaScript toSource() (see http://www.w3schools.com/jsref/jsref_toSource.asp) output format to JSON accepted format.  this works with subobjects too!
note: toSource() is part of JavaScript 1.3 but only implemented in Mozilla based javascript engines (not Opera/IE/Safari/Chrome).

<?php
  $str
= '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; // example javascript object toSource() output

 
$str = substr($str, 1, strlen($str) - 2); // remove outer ( and )
 
$str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names

 
$output = json_decode($str, true);
 
var_dump($output);
?>

var_dump output:
array(6) {
  ["strvar"]=>
  string(6) "string"
  ["number"]=>
  int(40)
  ["boolvar"]=>
  bool(true)
  ["subobject"]=>
  array(3) {
    ["substrvar"]=>
    string(10) "sub string"
    ["subsubobj"]=>
    array(1) {
      ["deep"]=>
      string(13) "deeply nested"
    }
    ["strnum"]=>
    string(2) "56"
  }
  ["false_val"]=>
  bool(false)
  ["false_str"]=>
  string(5) "false"
}

hope this saves someone some time.
jan at hooda dot de
21.12.2008 5:20
This function will convert a "normal" json to an array.

<?php
  
function json_code ($json) { 

     
//remove curly brackets to beware from regex errors

     
$json = substr($json, strpos($json,'{')+1, strlen($json));
     
$json = substr($json, 0, strrpos($json,'}'));
     
$json = preg_replace('/(^|,)([\\s\\t]*)([^:]*) (([\\s\\t]*)):(([\\s\\t]*))/s', '$1"$3"$4:', trim($json));

      return
json_decode('{'.$json.'}', true);
   } 

  
$json_data = '{
      a: 1,
      b: 245,
      c with whitespaces: "test me",
      d: "function () { echo \"test\" }",
      e: 5.66
   }'


  
$jarr = json_code($json_data);
?>
Aaron Kardell
14.11.2008 4:39
Make sure you pass in utf8 content, or json_decode may error out and just return a null value.  For a particular web service I was using, I had to do the following:

<?php
$contents
= file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents);
?>

Hope this helps!
steven at acko dot net
7.10.2008 9:49
json_decode()'s handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded or not. Observe the following examples, none of which contain valid JSON:

The following each returns NULL, as you might expect:

<?php
var_dump
(json_decode('['));             // unmatched bracket
var_dump(json_decode('{'));             // unmatched brace
var_dump(json_decode('{}}'));           // unmatched brace
var_dump(json_decode('{error error}')); // invalid object key/value
notation
var_dump
(json_decode('["\"]'));         // unclosed string
var_dump(json_decode('[" \x "]'));      // invalid escape code

Yet the following each returns the literal string you passed to it:

var_dump(json_decode(' [')); // unmatched bracket
var_dump(json_decode(' {')); // unmatched brace
var_dump(json_decode(' {}}')); // unmatched brace
var_dump(json_decode(' {error error}')); // invalid object key/value notation
var_dump(json_decode('"\"')); // unclosed string
var_dump(json_decode('" \x "')); // invalid escape code
?>

(this is on PHP 5.2.6)

Reported as a bug, but oddly enough, it was closed as not a bug.

[NOTE BY danbrown AT php DOT net: This was later re-evaluated and it was determined that an issue did in fact exist, and was patched by members of the Development Team.  See http://bugs.php.net/bug.php?id=45989 for details.]
jrevillini
26.09.2008 21:01
When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database.

I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes.  If the page with the form did not have

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

in the head, then the data was sent to the database with the wrong encoding.  Then, when json_decode tried to convert the string to an object, it failed every time.
soapergem at gmail dot com
23.08.2008 20:59
There have been a couple of comments now alerting us to the fact that certain expressions that are valid JavaScript code are not permitted within json_decode. However, keep in mind that JSON is ***not*** JavaScript, but instead just a subset of JavaScript. As far as I can tell, this function is only allowing whatever is explicitly outlined in RFC 4627, the JSON spec.

For instance, ganswijk, the reason you can't use single quotes to enclose strings is because the spec makes no mention of allowing single quotes (and therefore they are not allowed). And the issue of adding an extra comma at the end of an array is likewise not technically permitted in strict JSON, even though it will work in JavaScript.

And xris, while the example you provided with an unenclosed string key within an object is valid JavaScript, JavaScript != JSON. If you read it closely, you'll see that the JSON spec clearly does not allow this. All JSON object keys must be enclosed in double-quotes.

Basically, if there's ever any question for what is permitted, just read the JSON spec: http://tools.ietf.org/html/rfc4627
bizarr3_2006 at yahoo dot com
6.08.2008 16:47
If json_decode() failes, returns null, or returns 1, you should check the data you are sending to decode...

Check this online JSON validator... It sure helped me a lot.

http://www.jsonlint.com/
ganswijk at xs4all dot nl
7.07.2008 4:42
It was quite hard to figure out the allowed Javascript formats. Some extra remarks:

json_decode() doesn't seem to allow single quotes:
<?php
print_r
(json_decode('[0,{"a":"a","b":"b"},2,3]'));  //works
print_r(json_decode("[0,{'a':'a','b':'b'},2,3]"));  //doesn't work
?>

json_decode() doesn't allow an extra comma in a list of entries:
<?php
print_r
(json_decode('[0,1 ]'));  //works
print_r(json_decode('[0,1,]'));  //doesn't work
?>

(I like to write a comma behind every entry when the entries are spread over several lines.)

json_decode() does allow linefeeds in the data!
?>
xris / a t/ basilicom.de
27.06.2008 17:48
Please note: in javascript, the following is a valid object:
<?php
  
{ bar: "baz" }
?>

While PHP needs double quotes:

<?php
 
{ "bar": "baz" }
?>
phpben
16.04.2008 9:18
Re requiring to escape the forward slash:

I think PHP 5.2.1 had that problem, as I remember it occurring here when I posted that comment; but now I'm on 5.2.5 it doesn't, so it has obviously been fixed. The JSON one gets from all the browsers escape the forward slashes anyway.
steve at weblite dot ca
25.01.2008 0:25
For JSON support in older versions of PHP you can use the Services_JSON class, available at http://pear.php.net/pepr/pepr-proposal-show.php?id=198

<?php
if ( !function_exists('json_decode') ){
    function
json_decode($content, $assoc=false){
                require_once
'Services/JSON.php';
                if (
$assoc ){
                   
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                   
$json = new Services_JSON;
                }
        return
$json->decode($content);
    }
}

if ( !
function_exists('json_encode') ){
    function
json_encode($content){
                require_once
'Services/JSON.php';
               
$json = new Services_JSON;
               
        return
$json->encode($content);
    }
}
?>
yasarbayar at gmail dot com
26.07.2007 11:13
It took me a while to find the right JSON string format grabbed from mysql to be used in json_decode(). Here is what i came up with:

Bad(s) (return NULL):
{30:'13',31:'14',32:'15'}
{[30:'13',31:'14',32:'15']}
{["30":"13","31":"14","32":"15"]}

Good :
[{"30":"13","31":"14","32":"15"}]

returns:
array(1) { [0]=>  array(3) { [30]=>  string(2) "13" [31]=>  string(2) "14" [32]=>  string(2) "15" } }

hope this saves sometime..
nospam (AT) hjcms (DOT) de
22.04.2007 18:15
You can't transport Objects or serialize Classes, json_* replace it bei stdClass!
<?php

$dom
= new DomDocument( '1.0', 'utf-8' );
$body = $dom->appendChild( $dom->createElement( "body" ) );
$body->appendChild( $dom->createElement( "forward", "Hallo" ) );

$JSON_STRING = json_encode(
   array(
     
"aArray" => range( "a", "z" ),
     
"bArray" => range( 1, 50 ),
     
"cArray" => range( 1, 50, 5 ),
     
"String" => "Value",
     
"stdClass" => $dom,
     
"XML" => $dom->saveXML()
   )
);

unset(
$dom );

$Search = "XML";
$MyStdClass = json_decode( $JSON_STRING );
// var_dump( "<pre>" , $MyStdClass , "</pre>" );

try {

   throw new
Exception( "$Search isn't a Instance of 'stdClass' Class by json_decode()." );

   if (
$MyStdClass->$Search instanceof $MyStdClass )
     
var_dump( "<pre>instanceof:" , $MyStdClass->$Search , "</pre>" );

} catch(
Exception $ErrorHandle ) {

   echo
$ErrorHandle->getMessage();

   if (
property_exists( $MyStdClass, $Search ) ) {
     
$dom = new DomDocument( "1.0", "utf-8" );
     
$dom->loadXML( $MyStdClass->$Search );
     
$body = $dom->getElementsByTagName( "body" )->item(0);
     
$body->appendChild( $dom->createElement( "rewind", "Nice" ) );
     
var_dump( htmlentities( $dom->saveXML(), ENT_QUOTES, 'utf-8' ) );
   }
}

?>
paul at sfdio dot com
21.01.2007 4:08
I've written a javascript function to get around this functions limitations and the limitations imposed by IE's lack of native support for json serialization. Rather than converting variables to a json formatted string to transfer them to the server this function converts any javascript variable to a string serialized for use as POST or GET data.

String js2php(Mixed);

js2php({foo:true, bar:false, baz: {a:1, b:2, c:[1, 2, 3]}}));

will return:

foo=true&bar=false&baz[a]=1&baz[b]=2&baz[c][0]=1&...etc

function js2php(obj,path,new_path) {
  if (typeof(path) == 'undefined') var path=[];
  if (typeof(new_path) != 'undefined') path.push(new_path);
  var post_str = [];
  if (typeof(obj) == 'array' || typeof(obj) == 'object') {
    for (var n in obj) {
      post_str.push(js2php(obj[n],path,n));
    }
  }
  else if (typeof(obj) != 'function') {
    var base = path.shift();
    post_str.push(base + (path.length > 0 ? '[' + path.join('][') + ']' : '') + '=' + encodeURI(obj));
    path.unshift(base);
  }
  path.pop();
  return post_str.join('&');
}
Adrian Ziemkowski
13.12.2006 20:52
Beware when decoding JSON from JavaScript.  Almost nobody uses quotes for object property names and none of the major browsers require it, but this function does!   {a:1} will decode as NULL, whereas the ugly {"a":1} will decode correctly.   Luckily the browsers accept the specification-style quotes as well.
giunta dot gaetano at sea-aeroportimilano dot it
4.09.2006 17:16
Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.

If you expect to receive json data comprising characters outside the ascii range, be sure to use utf8_decode to convert them:

$php_vlaues = utf8_decode(json_decode($somedata))
giunta dot gaetano at sea-aeroportimilano dot it
4.09.2006 12:20
Please note that this function does NOT convert back to PHP values all strings resulting from a call to json-encode.

Since the json spec says that "A JSON text is a serialized object or array", this function will return NULL when decoding any json string that does not represent either an object or an array.

To successfully encode + decode single php values such as strings, booleans, integers or floats, you will have to wrap them in an array before converting them.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)