函数文档

wp_remote_fopen()

💡 云策文档标注

概述

wp_remote_fopen() 是一个 WordPress 函数,用于通过 HTTP GET 请求获取指定 URI 的内容。它封装了安全请求和错误处理,返回内容字符串或失败时返回 false。

关键要点

  • 函数 wp_remote_fopen($uri) 接收一个必需的 URI 字符串参数,用于指定要获取的网页地址。
  • 返回值为字符串(HTTP 内容)或 false(失败时)。
  • 内部使用 wp_safe_remote_get() 进行安全 HTTP 请求,并设置超时为 10 秒。
  • 通过 wp_remote_retrieve_body() 提取响应体,并使用 is_wp_error() 检查错误。
  • 如果 URI 解析失败或请求出错,函数返回 false。

代码示例

function wp_remote_fopen( $uri ) {
    $parsed_url = parse_url( $uri );

    if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
        return false;
    }

    $options            = array();
    $options['timeout'] = 10;

    $response = wp_safe_remote_get( $uri, $options );

    if ( is_wp_error( $response ) ) {
        return false;
    }

    return wp_remote_retrieve_body( $response );
}

注意事项

  • 此函数自 WordPress 1.5.1 版本引入。
  • 建议参考 Plugin Handbook: HTTP API 获取更多信息。
  • 相关函数包括 wp_safe_remote_get()、wp_remote_retrieve_body() 和 is_wp_error()。

📄 原文内容

HTTP request for URI to retrieve content.

Description

See also

Parameters

$uristringrequired
URI/URL of web page to retrieve.

Return

string|false HTTP content. False on failure.

More Information

See Plugin Handbook: HTTP API

Source

function wp_remote_fopen( $uri ) {
	$parsed_url = parse_url( $uri );

	if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
		return false;
	}

	$options            = array();
	$options['timeout'] = 10;

	$response = wp_safe_remote_get( $uri, $options );

	if ( is_wp_error( $response ) ) {
		return false;
	}

	return wp_remote_retrieve_body( $response );
}

Changelog

Version Description
1.5.1 Introduced.