Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use swedish letters with json_encode() in PHP?

Tags:

json

php

encoding

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?

like image 862
Weblurk Avatar asked Dec 04 '25 10:12

Weblurk


2 Answers

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.

like image 58
Shakti Singh Avatar answered Dec 05 '25 22:12

Shakti Singh


json_encode expects the input to be utf-8. Save your file as utf-8.

like image 25
troelskn Avatar answered Dec 05 '25 23:12

troelskn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!