Prova con qualcosa del genere (l'ho scritta ora quindi controlla che non vi siano errori e migliorala)
Codice PHP:
class htmlParser
{
protected $title;
protected $metas;
protected $source;
public function __construct($source)
{
if (!is_string($source))
{
throw new Exception('Il sorgente della pagina deve essere una stringa');
}
$this->source = $source;
}
public function getSource()
{
return $this->source;
}
public function getTitle($default = null)
{
if (!$this->title)
{
if (preg_match("/<title>([^>]*)<\/title>/i", $this->source, $title))
{
$this->title = strip_tags($title[1]);
}
else
{
$this->title = $default;
}
}
return $this->title;
}
public function getMetas()
{
if (!$this->metas)
{
if (preg_match_all("/<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>/i", $this->source, $metas))
{
$count = count($metas[0]);
$res = array();
for ($i = 0; $i < $count; $i++)
{
$res[strtolower(trim($metas[1][$i]))] = trim($metas[2][$i]);
}
$this->metas = $res;
}
else
{
$this->metas = array();
}
}
return $this->metas;
}
public function getMeta($meta, $default = null)
{
if ($this->hasMeta($meta))
{
return $this->metas[strtolower($meta)];
}
return $default;
}
public function hasMeta($meta)
{
if (!$this->metas)
{
$this->getMetas();
}
return (bool) isset($this->metas[strtolower($meta)]);
}
}
$hp = new htmlParser(file_get_contents('http://www.sitochevuoitu.it'));
echo 'Titolo => ' . $hp->getTitle('Nessun titolo') . '
';
echo 'Descrizione => ' . $hp->getMeta('description', 'Nessuna descrizione');
Ti scrivo qui le due espressioni sperando che non le modifichi:
"/<title>([^>]*)<\/title>/i"
"/<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>/i"