<?php

function get_url_metadata($url) {
  $metadata = array();

  // 1. Fetch the HTML content of the URL
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
  curl_setopt($ch, CURLOPT_USERAGENT, 'Your_Bot_Name'); // Set a user agent
  $html = curl_exec($ch);
  curl_close($ch);

  if ($html === false) {
    return $metadata; // Handle errors gracefully
  }

  // 2. Use a DOM parser to extract data
  $doc = new DOMDocument();
  @$doc->loadHTML($html); // Suppress warnings on invalid HTML

  // 2.1 Extract title
  $title_tags = $doc->getElementsByTagName('title');
  if ($title_tags->length > 0) {
    $metadata['title'] = $title_tags->item(0)->nodeValue;
  }

  // 2.2 Extract meta tags
  $meta_tags = $doc->getElementsByTagName('meta');
  foreach ($meta_tags as $meta) {
    $property = $meta->getAttribute('property');
    $name = $meta->getAttribute('name');
    $content = $meta->getAttribute('content');

    if (!empty($property)) {
      $metadata[$property] = $content;
    } elseif (!empty($name)) {
      $metadata[$name] = $content;
    }
  }

  // 2.3 Extract description (common case)
  if (isset($metadata['og:description']) || isset($metadata['description'])) {
    $metadata['description'] = isset($metadata['og:description']) ? $metadata['og:description'] : $metadata['description'];
  }

  // 2.4 Extract image (common case)
  if (isset($metadata['og:image'])) {
    $metadata['image'] = $metadata['og:image'];
  }

  return $metadata;
}

// Example usage:
$url = 'https://www.google.com';
$metadata = get_url_metadata($url);

print_r($metadata);

?>
