如何用PHP提取JSON数据?从URL获取JSON提取拥堵信息失败
Hey there! Let's tackle this PHP JSON parsing issue step by step—since you mentioned online examples are too simple, I bet your traffic JSON has a nested structure that those basic snippets don't account for, which is why you're not getting results when trying to grab the first congestion entry.
Step 1: Properly Fetch & Parse the JSON
First, make sure you're correctly pulling and decoding the JSON data. Always add error checking here—this saves you from chasing ghosts if the JSON is malformed.
// Fetch JSON from your URL $jsonRaw = file_get_contents('your-traffic-data-url'); // Decode into an associative array (the second `true` parameter is critical!) $trafficData = json_decode($jsonRaw, true); // Check if parsing succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("Oops, JSON parsing failed: " . json_last_error_msg()); }
Step 2: Map Out Your JSON Structure
The most common issue here is not knowing where your congestion data lives in the nested hierarchy. Print the full parsed array to see the layout:
// Dump the structure to inspect it (remove this in production!) print_r($trafficData);
For example, your JSON might look something like this (super common for traffic APIs):
{ "status": "success", "data": { "traffic_updates": { "congestions": [ { "road": "Main Street", "severity": "Heavy", "delay": "12 mins" }, { "road": "Oak Avenue", "severity": "Moderate", "delay": "5 mins" } ], "road_closures": [...] } } }
Step 3: Extract & Display All Congestion Entries
Once you know the hierarchy, target the congestions array directly. Use null coalescing (??) to handle missing fields gracefully:
// Check if the congestion array exists and is valid if (isset($trafficData['data']['traffic_updates']['congestions']) && is_array($trafficData['data']['traffic_updates']['congestions'])) { $congestionList = $trafficData['data']['traffic_updates']['congestions']; // Output the results on your site echo "<h3>Current Traffic Congestion</h3>"; echo "<ul>"; foreach ($congestionList as $congestion) { // Safely get values (fallback to "Unknown" if missing) $road = $congestion['road'] ?? "Unknown Road"; $severity = $congestion['severity'] ?? "Unknown Severity"; $delay = $congestion['delay'] ?? "Unknown Delay"; echo "<li><strong>{$road}</strong>: {$severity} congestion, expected delay {$delay}</li>"; } echo "</ul>"; } else { echo "<p>No congestion reports available at this time.</p>"; }
Why Your First Entry Didn't Show Up
Here are the most likely culprits:
- Wrong hierarchy: You tried accessing
$trafficData['congestions']directly, but it's nested underdata > traffic_updates(or similar) - JSON parsing failed: You skipped error checking, so
$trafficDatawasnullall along - Case sensitivity: The JSON uses
Roadinstead ofroad, orCongestionsinstead ofcongestions - Root is an object, not an array: You tried using
$trafficData[0]but the top-level of your JSON is an object, not an array
内容的提问来源于stack exchange,提问作者Nour

