I have an array like this, which I json encode:
$regularArray = array(
array( "label" => "Hello World", "value" => 1 ),
array( "label" => "Hej Världen", "value" => 2 )
);
$jsonArray = json_encode( $regularArray );
("Hej världen" means hello world in swedish) But when I print $jsonArray I get this:
[{"label":"Hello World","value":1},{"label":null,"value":2}]
Why is the label null for the second item in the array? I know it has to do with the word "Världen" since it contains a non-standard letter. How can I get around this?
json_encode function only works with UTF-8 encoded data. You may change your input array data to UTF-8.
Encode the input array data using utf8_encode and decode it whenever you need the data using utf8_decode
<?php
$regularArray = array(
array( "label" => "Hello World", "value" => 1 ),
array( "label" => "Hej Världen", "value" => 2 )
);
$regularArray[1]['label'] = utf8_encode( $regularArray[1]['label']);
echo $jsonArray = json_encode( $regularArray );
$data = json_decode($jsonArray, true);
$data[1]['label'] = utf8_decode($data[1]['label']);
print_r($data);
?>
Output:-
[{"label":"Hello World","value":1},{"label":"Hej V\u00c3\u00a4rlden","value":2}]
Array
(
[0] => Array
(
[label] => Hello World
[value] => 1
)
[1] => Array
(
[label] => Hej Världen
[value] => 2
)
)
I made a Test Page, it works fine.
json_encode expects the input to be utf-8. Save your file as utf-8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With