PHP Echo First Paragraph

Sitebee

Technical SEO
Staff member
The PHP snippet below scrapes the current URL to extract the first paragraph on the page. The can be useful for creating Excerpts and creating dynamic meta descriptions.

Code:
<?php 
// build paths
$route1="https://$_SERVER[HTTP_HOST]";
$route2 = explode ('/', $_SERVER[REQUEST_URI])[1];
$route3 = explode ('/', $_SERVER[REQUEST_URI])[2];

// concatenate paths
$fullroute = $route1 . '/' . $route2 . '/' . $route3;
// Get current URL contents
$content = file_get_contents($fullroute);

// load the content
$dom = new domdocument();
$dom->loadhtml($content);

// output first paragraph
$firstpara = $dom->getElementsByTagName('p');
echo " {$firstpara->item(0)->nodeValue}\n";

?>