What is the best method to retrieve the title tag of an external page using the http api?

The snippet below will get the body but I can’t find the right documentation about how to just get the tag. :/

$url="http://wordpres.org";
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
   echo 'Something went wrong!';
} else {
print wp_remote_retrieve_body( $response );
}

Edit: This code snippet gets both the screenshot
and title of an external page (Thanks again @Bainternet). With a
little editing this could be an easy
way to display the link post format.

<?php 
$content = get_the_content();
$url = strip_tags($content); //assumes only a url is in the_content
$width="150";
$cleanurl = urlencode(clean_url($url));
$fullurl="http://s.wordpress.com/mshots/v1/" . $cleanurl . '?w=' . $width;

// return title tag of an external page
// http://wordpress.stackexchange.com/questions/19424/how-to-get-title-tag-of-an-external-page-with-http-api
function get_page_title($url){
    if( !class_exists( 'WP_Http' ) )
        include_once( ABSPATH . WPINC. '/class-http.php' );
    $request = new WP_Http;
    $result = $request->request( $url );
    if( is_wp_error( $result ) )
        return false;

    if( preg_match("#<title>(.+)<\/title>#iU", $result['body'], $t))  {
        return trim($t[1]);
    } else { 
return false; }
    }
$title = get_page_title($url);      

echo '<div class="grid_4 alpha"><a href="' . $url . '"><img src="' . $fullurl . '" width="' . $width .'px" /></a></div>'; 
echo '<div class="grid_10 omega"><h3>'; if ($title !== false){ echo $title;} echo '</h3><p>' . $content . '</p></div>';
echo '<div class="clear"></div>';
?>

2 Answers
2

here is a function i have for that:

function get_page_title($url){
        if( !class_exists( 'WP_Http' ) )
            include_once( ABSPATH . WPINC. '/class-http.php' );
        $request = new WP_Http;
        $result = $request->request( $url );
        if( is_wp_error( $result ) )
            return false;

        if( preg_match("#<title>(.+)<\/title>#iU", $result['body'], $t))  {
            return trim($t[1]);
        } else {
            return false;
        }
    }

Usage:

$title = get_page_title('http://www.google.com');
if ($title !== false){ echo $title;}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *