Horje
PHP Extract Meta Title Description Keyword Ogimage from URL
To extract the title, description, and keywords from a webpage's meta tags using PHP, you can utilize the DOMDocument class.

Full Codes

Try it in your website. Just copy and run on index.php
index.php
Example: HTML
<?php
$targetUrl = 'https://w3schools.com'; // Replace with your target URL


function extractMetaInfo($url) {

$context = stream_context_create(
    array(
        "http" => array(
            "timeout" => 30,  //1200 Seconds is 20 Minutes            
            "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
        )
    )
);
    
    $html = @file_get_contents($url, false, $context); // Use @ to suppress warnings for failed requests

    if ($html === false) {
        return ['error' => 'Could not retrieve content from URL.'];
    }

    $dom = new DOMDocument();
    @$dom->loadHTML($html); // Use @ to suppress warnings for malformed HTML

// Extract Title
    $titleNodes = $dom->getElementsByTagName('title');
    if ($titleNodes->length > 0) {
        $metaData['title'] = $titleNodes->item(0)->nodeValue;
    }

    // Extract Meta Description and Keywords
    $metaNodes = $dom->getElementsByTagName('meta');
    foreach ($metaNodes as $meta) {
        
        // Meta for name
        $name = strtolower($meta->getAttribute('name'));
        $content = $meta->getAttribute('content');

        if ($name === 'description') {
            $metaData['description'] = $content;
        }
        
        if ($name === 'keywords') {
            $metaData['keywords'] = $content;
        }     
        
        
        // Meta for Property
        $name_property = strtolower($meta->getAttribute('property'));
        $content = $meta->getAttribute('content');

        if ($name_property === 'og:image') {
            $metaData['ogimage'] = $content;
        }
        
        
            

    }

    return $metaData;
}

// Example usage:
$metaData = extractMetaInfo($targetUrl);

if (isset($metaData['error'])) {
    echo $metaData['error'];
} else {
    echo "Title: " . $metaData['title'] . "\n";
    echo '</br>';
    echo "Description: " . $metaData['description'] . "\n";
        echo '</br>';
    echo "Keywords: " . $metaData['keywords'] . "\n";
        echo '</br>';
        echo "Og Image: " . $metaData['ogimage'] . "\n";

    
}

?>

Output should be:





php function

Type:
Develop
Category:
Web Tutorial
Sub Category:
PHP Function Tutorial
Uploaded by:
Admin