函数文档

wp_remote_retrieve_body()

💡 云策文档标注

概述

wp_remote_retrieve_body() 是 WordPress HTTP API 中的一个函数,用于从 HTTP 响应中提取 body 部分。它处理 WP_Error 或无效响应,确保安全返回字符串。

关键要点

  • 函数接受一个参数 $response,类型为 array 或 WP_Error,表示 HTTP 响应。
  • 返回值为字符串,即响应的 body 内容;如果 $response 是 WP_Error 或未设置 body,则返回空字符串。
  • 内部实现检查 is_wp_error() 和 isset($response['body']),以增强健壮性。
  • 常用于处理远程 API 调用,如 JSON 数据解析。

代码示例

$url      = 'http://example.org/api';
$response = wp_remote_get( esc_url_raw( $url ) );
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );

注意事项

  • 直接访问 wp_remote_get() 返回数组的 ['body'] 键可能引发 PHP 错误通知,如果响应失败;使用 wp_remote_retrieve_body() 可避免此问题。
  • 性能优化建议:虽然可以直接访问数组,但使用函数能提供更好的错误处理,不建议跳过函数调用以牺牲安全性。

📄 原文内容

Retrieves only the body from the raw response.

Parameters

$responsearray|WP_Errorrequired
HTTP response.

Return

string The body of the response. Empty string if no body or incorrect parameter given.

Source

function wp_remote_retrieve_body( $response ) {
	if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
		return '';
	}

	return $response['body'];
}

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example

    Retrieving data from a JSON API:

    $url      = 'http://example.org/api';
    $response = wp_remote_get( esc_url_raw( $url ) );
    
    /* Will result in $api_response being an array of data,
    parsed from the JSON response of the API listed above */
    $api_response = json_decode( wp_remote_retrieve_body( $response ), true );

  2. Skip to note 4 content

    Better performance?

    Skip the extra function call and get the body (or any other part of the returned array) from wp_remote_get() . That’s essentially what wp_remote_retrieve_body() is doing.

    $url  = 'https://example.com/';
    $body = wp_remote_get( esc_url_raw( $url ) )['body'];