wp_remote_get vs. file_get_contents vs. cURL?
Always use wp_remote_get when in a WordPress context. It figures out the correct way, be it curl or something else, and uses that. Simple.
Always use wp_remote_get when in a WordPress context. It figures out the correct way, be it curl or something else, and uses that. Simple.
To make wp_remote_get() work you need to check your php.ini file. In your php.ini file you need to set allow_url_include = On, which by default is set as allow_url_include = Off. Otherwise wp_remote_get() will not work. Reference: allow_url_include
// make request… (optionally save in transient for faster future fetches) $dom = new DOMDocument(); $dom->loadHTML(wp_remote_retrieve_body($request)); $sections=$dom->getElementsByTagName(“section”); foreach ($sections as $section) { // Do something… }
You can try this: foreach( $posts as $post ) { $url = sprintf( ‘http://graph.facebook.com/?id=%s’, get_permalink( $post->ID ) ); $response = wp_remote_get( $url, array( ‘timeout’ => 15 ) ); if( ! is_wp_error( $response ) && isset( $response[‘response’][‘code’] ) && 200 === $response[‘response’][‘code’] ) { $body = wp_remote_retrieve_body( $response ); $fb = json_decode( $body ); if( ! … Read more
It is possible to do HTTP DIGEST authentication with wp_remote_get(), but it’s somewhat complicated. I’ve written a short wrapper function you can use.
wp_upload_bits() uses wp_upload_dir() which fires the upload_dir filter allowing you to modify the upload directory’s path, sub-directory and URL. So you can use that filter to “force” wp_upload_bits() to use a custom path by doing something like: // Demo to get the image data. $url=”https://logo.clearbit.com/starcomww.com”; $content = file_get_contents( $url ); $_filter = true; // For … Read more
If you want to send Affiliate-Id and Affiliate-Token in headers then you need to pass them in the optional arguments of wp_remote_get function. Example: $response = wp_remote_get( $api_url , array( ‘timeout’ => 10, ‘headers’ => array( ‘Affiliate-Id’ => XXXXX, ‘Affiliate-Token’=> XXXXX ) ));
Well here’s the solution that I came up with: // Use wp_remote_get to fetch the data $response = wp_remote_get($url); // Save the body part to a variable $zip = $data[‘body’]; // In the header info is the name of the XML or CVS file. I used preg_match to find it preg_match(“/.datafeed_([0-9]*)\../”, $response[‘headers’][‘content-disposition’], $match); // Create … Read more
If you need to send a JSON response, then there’s a set of functions for that. In case you need that for an AJAX callback: wp_remote_retrieve_response_message() wp_remote_retrieve_response_code() wp_send_json_success() wp_send_json_error() wp_send_json() Would finally be something like that: $request = wp_remote_get( ‘http://example.com’ ); $response = wp_remote_retrieve_body( $request ); if ( ‘OK’ !== wp_remote_retrieve_response_message( $response ) OR 200 … Read more