如何修改CURL请求YOURLS API的代码以提取shorturl值?
Extract Only
shorturl from YOURLS API CURL Response Got it, let's adjust your code to pull just the shorturl value instead of echoing the entire API response. Here's how to do it step by step:
Key Background
The YOURLS API returns data in JSON format (as long as you specify format=json in your POST fields), so we just need to decode that JSON string and target the specific key we want.
Modified Code
Here's the full adjusted code snippet, with comments explaining the new parts:
// Init the CURL session $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $api_url ); curl_setopt( $ch, CURLOPT_HEADER, 0 ); // No header in the result curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // Return, do not echo result curl_setopt( $ch, CURLOPT_POST, 1 ); // This is a POST request curl_setopt( $ch, CURLOPT_POSTFIELDS, array( // Fill in your required YOURLS API data here 'url' => 'https://your-long-url-to-shorten.com', 'action' => 'shorturl', 'format' => 'json', // Critical: Ensures response is JSON-decodable 'username' => 'your-yourls-username', 'password' => 'your-yourls-password' ) ); // Execute the CURL request and get raw response $data = curl_exec($ch); // Clean up the CURL session curl_close($ch); // Decode JSON response into an associative array $response = json_decode($data, true); // Extract and output only the shorturl (with error handling) if (isset($response['shorturl'])) { echo $response['shorturl']; } else { // Handle errors gracefully - YOURLS often returns a message for failures if (isset($response['message'])) { echo "Failed to get short URL: " . $response['message']; } else { echo "Error: Invalid or unexpected API response"; } }
What Changed?
- Added JSON decoding:
json_decode($data, true)converts the raw JSON string into a PHP associative array, making it easy to access specific values. - Targeted
shorturlextraction: Instead of echoing the whole$datastring, we check if theshorturlkey exists in the decoded array and output only that value. - Error handling: The
isset()checks prevent PHP warnings if the API returns an error (like invalid credentials or a malformed URL) and gives you meaningful feedback.
Critical Note
Don't forget to include 'format' => 'json' in your POST fields! YOURLS defaults to returning HTML for responses, which won't work with json_decode().
内容的提问来源于stack exchange,提问作者DigiNet Events
相关产品推荐
相关产品推荐

