1

I'm very new to PHP and JSON, so I hope you'll excuse my (probably) stupid question. I'm trying to create a new JSON with fundamental information for my needings, using the information returned by Google Maps API. Here's the code:

<?php
/**
 * Created by PhpStorm.
 * User: biagiomontesano
 * Date: 22/10/15
 * Time: 18:16
 */

function selectLongestSteps($steps_txt, $min_meters)
{
    $steps = JSON.parse($steps_txt);
    //$steps = json_decode($steps_txt, true);
    //$steps = $steps_txt;
    echo 'Num of steps: ' . count($steps[0]);
}

function createJsonFromResponse($response_json)
{
    // output json
    $output_json = '[';

    // number of steps
    $num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
    //echo $num_steps;

    // fill the json
    for($i = 0; $i<$num_steps; $i++)
    {
        // start parenthesis
        $output_json .= '{';

        // start latitude
        $output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';

        // start longitude
        $output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';

        // end latitude
        $output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';

        // end latitude
        $output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';

        // step length
        $output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value']. ',';

        // html instruction
        $output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';

        // closure parenthesis
        $output_json .= '}';

        // insert comma if required
        if($i != $num_steps-1)
            $output_json .= ',';

    }

    $output_json .= ']';

    return $output_json;
}

function get_driving_information($start, $finish)
{
    if (strcmp($start, $finish) != 0) {
        $start = urlencode($start);
        $finish = urlencode($finish);

        $url = 'http://maps.googleapis.com/maps/api/directions/json?origin=' . $start . '&destination=' . $finish . '&sensor=false';

        // get the json response
        $resp_json = file_get_contents($url);

        // decode the json
        $resp = json_decode($resp_json, true);

        return $resp;
    }

    else
        return null;

}




try
{
    $info = get_driving_information('via Tiburtina 538, Roma', 'via Ariosto 25, Roma');
    $steps = null;
    if(!$info)
        echo 'No info';

    else
         $steps = createJsonFromResponse($info);

    selectLongestSteps($steps, 200);
    //echo $steps;
}
catch(Exception $e)
{
    echo 'Caught exception: '.$e->getMessage()."\n";
}

As a test, I asked my function selectLongestSteps to display the number of elements in the JSON. As you see, I tried to initialise variable $steps in 3 different ways: the last two return a wrong results (0 or 1, while result should be 18). The first one, that I found on web, returns the following error:

Notice: Use of undefined constant JSON - assumed 'JSON' in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11

Fatal error: Call to undefined function parse() in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11

I suspect the problem is in creating JSON inside the other function. Can you help?

Thanks

2 Answers 2

3

The problem is this line:

$steps = JSON.parse($steps_txt);

JSON.parse() ist a JavaScript function. You need something like this in PHP

$steps = json_decode($steps_txt);

http://php.net/manual/en/function.json-decode.php

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for help. as you can see from commented code, I already tried this kind od solution, but I get 0 as the number of element in the most external array inside JSON. maybe it be a problem in creating it, in function createJsonFromResponse, that forbids first function to recognise all the elements inside JSON?
2

PHP has in-built function to change array to json and vice-verse.

json_encode($array) will give json form of array.

json_decode($json, true) will give your array back from json. If you didn't give true as your second param, you will be getting an object instead of an array.

1 Comment

thanks for help. as you can see from commented code, I already tried this kind od solution, but I get 0 as the number of element in the most external array inside JSON. maybe it be a problem in creating it, in function createJsonFromResponse, that forbids first function to recognise all the elements inside JSON?

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.