0

Here is my json string:

{
"routes": [
    {
        "bounds": {
            "northeast": {
                "lat": 41.9291739,
                "lng": 23.7293099
            },
            "southwest": {
                "lat": 37.9103506,
                "lng": 12.4822041
            }
        },
        "copyrights": "Map data,google",
        "legs": [
            {
                "distance": {
                    "text": "1,250 km",
                    "value": 1249958
                }
            }
        ]
    }
]
}

i want to get routes->legs->distance->value im using this code unsuccessfully:

$json = json_decode(file_get_contents('./test.txt'));
$distance = $json->routes[0]->legs[0]->distance->value;
var_dump($distance);

any ideas?

8
  • 1
    That looks correct and should work. What error do you get (if any)? Commented Oct 23, 2013 at 13:01
  • im getting: Notice: Trying to get property of non-object Commented Oct 23, 2013 at 13:07
  • But json_decode() only works with php 5.2 or greater. What is your php version? phpinfo(); Commented Oct 23, 2013 at 13:08
  • it's on wamp and php version is 5.4.2 Commented Oct 23, 2013 at 13:12
  • @mike_x_: What does var_dump( file_exists('test.txt') ); output? Commented Oct 23, 2013 at 13:21

1 Answer 1

2

I think you're having problems reading your file, the code below works.

Does the file exist in the same dir? Does your file has the json content? Maybe you don't have permission on the file.

<?php

$json=json_decode('{
"routes": [
    {
        "bounds": {
            "northeast": {
                "lat": 41.9291739,
                "lng": 23.7293099
            },
            "southwest": {
                "lat": 37.9103506,
                "lng": 12.4822041
            }
        },
        "copyrights": "Map data,google",
        "legs": [
            {
                "distance": {
                    "text": "1,250 km",
                    "value": 1249958
                }
            }
        ]
    }
]
}');

$distance = $json->routes[0]->legs[0]->distance->value;
var_dump($distance);
Sign up to request clarification or add additional context in comments.

1 Comment

if i add it as string it works for me too... i also changed encoding but no luck...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.