PHP如何从Curl返回的JSON结果提取并显示name字段?
Hey there! I see you're trying to pull the name field from the Riot API response using PHP and Curl, but you're currently just dumping the whole decoded JSON. Let's adjust your code to make this work properly, and fix a small syntax issue along the way.
First, Fix the URL Syntax Error
Looking at your original code, the URL line has a quote nesting problem that will throw a syntax error:
$url="https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/alphamonkey95?api_key="myapikey";
You can't use unescaped double quotes inside a double-quoted string. Instead, either write your API key directly in the string, or concatenate it properly (especially if you store the key in a variable for better maintainability):
// If your API key is a literal string $url = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/alphamonkey95?api_key=myapikey"; // If your API key is stored in a variable (recommended!) $apiKey = "your_actual_api_key_here"; $url = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/alphamonkey95?api_key=" . $apiKey;
Extract the 'name' Field from the JSON Response
Once your Curl request runs successfully, json_decode($result, true) converts the JSON into an associative array. You can directly access the name field using array notation. We'll also add error handling to avoid crashes if the request fails or the response isn't valid JSON.
Here's the full, working code:
<?php // Set up your URL with the correct API key $apiKey = "your_actual_api_key_here"; $url = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/alphamonkey95?api_key=" . $apiKey; // Initialize Curl $ch = curl_init(); // Configure Curl options curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Note: Disable only for testing—enable in production! curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute the request $result = curl_exec($ch); // Check for Curl errors if(curl_errno($ch)){ echo "Curl Error: " . curl_error($ch); curl_close($ch); exit; } // Close the Curl handle curl_close($ch); // Decode JSON into an associative array $decodedData = json_decode($result, true); // Verify JSON decoding worked if($decodedData === null){ echo "Failed to parse JSON response"; exit; } // Extract and display the 'name' field if(isset($decodedData['name'])){ echo "Summoner Name: " . $decodedData['name']; } else { echo "The 'name' field was not found in the API response"; } ?>
Quick Notes:
- SSL Verification: Disabling
CURLOPT_SSL_VERIFYPEERis fine for testing, but in production, enable it (set totrue) to keep your requests secure. Ensure your server has valid SSL certificates installed. - Error Handling: The added checks help you debug common issues like invalid API keys, rate limits, or non-existent summoners.
内容的提问来源于stack exchange,提问作者James

