獲取遠端 JSON 資源

此程式碼段將獲取 JSON 格式的資源,對其進行解碼並以 PHP 陣列格式列印。

// Fetch 
$response = wp_remote_get( 'http://www.example.com/resource.json' );

if ( ! is_wp_error( $response ) ) {
  $headers = wp_remote_retrieve_headers( $response );

  if ( isset( $headers[ 'content-type' ] ) && 'application/json' === $headers[ 'content-type' ] ) {
    print_r( json_decode( wp_remote_retrieve_body( $response ) ) );
  }
}