php - Retrieve string from json

282

I'm trying to retrieve a URL string from some json code.

Here is the json code

    {"files":["www.example1.com"],"previews":["www.example1preview.com"],"meta":{},"userId":"guest","product":{"id":"2335","name":"standard"},"type":"u"}

Looking at what I've seen in the PHP manual I'm trying to retrieve previews like this.

    <?php
    ob_start();
    include('getjson.php');
    $meta_value_json = ob_get_clean();

    echo $meta_value_json;

    $meta_value_json = json_decode($meta_value_json);
    print $meta_value_json->{'previews'};

    ?>

This doesn't seem to output the value however.

520

Answer

Solution:

By experimenting with php -a command on terminal, I've put your json into json_decode and managed to get your link by just doing:

print $meta_value_json->previews[0];

The only reason to use print $meta_value_json->{'previews'}; at least according to php documentation is if you want an object as output and the key trying to retrieve is numerical or of a type that is not supported by php.

By experimenting a bit further, the reason that print $meta_value_json->{'previews'}; fails is because print expects a string, in our case here previews is an array. Therefore if you do print $meta_value_json->{'previews'}[0]; it will also work as expected.

27

Answer

Solution:

You need to get the value from your decoded json like this: $class->parameter. Knowing that previews is an array, you will also need to choose a specific element from it to print ( I got the first one ):

   <?php
    ob_start();
    include('getjson.php');
    $meta_value_json = ob_get_clean();

    echo $meta_value_json;

    $meta_value_json = json_decode($meta_value_json);
    print $meta_value_json->previews[0]; /// get the specific value

    ?>

People are also looking for solutions to the problem: php - Javascript -Way to detect on what option user clicks on Navigation Popup

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.