You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 shorturl extraction: Instead of echoing the whole $data string, we check if the shorturl key 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:12:33