how to get data to javascript from php using json_encode?

how to get data to javascript from php using json_encode?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoding JSON Structures for Google Maps Integration

You have a PHP array containing traceroute data where each element represents a hop in the path, holding the IP address and corresponding latitude/longitude coordinates. Your goal is to visualize this on Google Maps, but you're running into a structural mismatch between your current output format and the object-oriented style you prefer in JavaScript. The core issue stems from how json_encode handles associative arrays versus indexed arrays.

When you use JSON_FORCE_OBJECT in PHP, you force every element of the array to be treated as an associative object (a dictionary) rather than a simple index-based list. While this works well if your data is inherently keyed by name, it creates a flat structure when serialized. The resulting JSON string looks like this:

{"ip":"192.0.2.1","latitude":45.0,"longitude":-90.0,"ip":"198.51.100.1","latitude":46.0,"longitude":-91.0}

This is not a valid JSON array of objects; it is a single, flattened associative object containing multiple properties. To access the second IP's location in JavaScript, you would have to use dot notation or bracket notation with specific keys like data.ip and data.latitude. However, this approach breaks down immediately when duplicate keys (like "ip" appearing twice) exist. JavaScript objects cannot have duplicate keys; if two values share the same key name, the second one overwrites the first. Consequently, your script would only ever see the data for the target IP or the last hop in the route, losing the sequential nature of the traceroute.

To replicate your previous workflow—where you accessed data[1].latitude—you must ensure that the PHP data is serialized as a JSON array of objects, not a single object. You need to remove the JSON_FORCE_OBJECT flag from your json_encode call. By default, json_encode treats indexed arrays as JSON arrays:

$json = json_encode($c);
// Or explicitly without flags if you are on PHP 5.4+
// $json = json_encode($c, JSON_UNESCAPED_UNICODE); 

If $c is an indexed array like ['ip' => '...', 'lat' => '...', 'lng' => '...'], the output will be:

[{"ip":"192.0.2.1","latitude":45.0,"longitude":-90.0},{"ip":"198.51.100.1","latitude":46.0,"longitude":-91.0}]

This structure matches your legacy data12.route format perfectly. When you send this via an HTTP response or a JSON file, your JavaScript can parse it into a native array:

const json = '{"route":[{"ip":"...",...}]}'; // Example if wrapped in an object
// Or directly as an array string:
const rawJson = '[{"ip":"192.0.2.1","latitude":45.0,"longitude":-90.0},...]';

const data = JSON.parse(rawJson);
const route = data; // If the root is an array, or data.route if wrapped

In your specific case, since you previously accessed data[1].latitude, the PHP variable $c must be a standard indexed array. The resulting JavaScript object will naturally support numeric indexing. You can then iterate through the hops to populate markers:

const route = data; // Assuming $c was directly encoded as an array
for (let i = 0; i < route.length; i++) {
    const ip = route[i].ip;
    const lat = route[i].latitude;
    const lng = route[i].longitude;
    
    new google.maps.Marker({
        position: { lat: lat, lng: lng },
        map: map,
        title: ip
    });
}

If you are building a larger application where maintaining this flat array structure feels awkward, consider wrapping the data in an object with a route key, as shown in your old example. This provides a clear namespace for your traceroute data. In modern PHP development, especially within the Laravel ecosystem, you might find it helpful to utilize collection helpers or response facades to ensure consistent JSON serialization across your API endpoints. For instance, returning a structured response array often prevents accidental key collisions that flatten your data structure unintentionally.

The most critical takeaway is structural integrity: always verify whether your PHP data is an indexed list or an associative map before encoding. If you need sequential access in JavaScript, json_encode must produce a JSON array ([]), not a JSON object ({}). Removing the force-object flag restores the indexing capability you relied on previously, allowing you to cleanly map every hop of your traceroute onto the map interface.

Our network