From a5daebb6ba7e6dfee45ca262ff1845730040a241 Mon Sep 17 00:00:00 2001 From: shweshi Date: Thu, 11 Jan 2018 00:45:48 +0530 Subject: [PATCH] Added code to fetch open graph data --- .gitignore | 1 + composer.json | 19 +++++++++++ src/Facades/OpenGraphFacade.php | 13 ++++++++ src/OpenGraph.php | 49 +++++++++++++++++++++++++++++ src/Providers/OpenGraphProvider.php | 29 +++++++++++++++++ 5 files changed, 111 insertions(+) create mode 100644 .gitignore create mode 100644 composer.json create mode 100644 src/Facades/OpenGraphFacade.php create mode 100644 src/OpenGraph.php create mode 100644 src/Providers/OpenGraphProvider.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57872d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor/ diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..d9a0f70 --- /dev/null +++ b/composer.json @@ -0,0 +1,19 @@ +{ + "name": "shweshi/opengraph", + "description": "A Laravel package to fetch website Open Graph metadata.", + "type": "library", + "authors": [ + { + "name": "Shashi Prakash Gautam", + "email": "contactmespg@gmail.com" + } + ], + "require": {}, + + "autoload": { + "psr-4": { + "App\\": "app/", + "shweshi\\OpenGraph\\": "packages/shweshi/OpenGraph/src" + } + } +} diff --git a/src/Facades/OpenGraphFacade.php b/src/Facades/OpenGraphFacade.php new file mode 100644 index 0000000..0b1b7af --- /dev/null +++ b/src/Facades/OpenGraphFacade.php @@ -0,0 +1,13 @@ +curl_get_contents($url); + + /** + * parsing starts here: + */ + $doc = new DOMDocument(); + @$doc->loadHTML($html); + + + $tags = $doc->getElementsByTagName('meta'); + $metadata = array(); + + foreach ($tags as $tag) { + if ($tag->hasAttribute('property') && strpos($tag->getAttribute('property'), 'og:') === 0) { + $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_'); + $value = $tag->getAttribute('content'); + } + if (!empty($key)) { + $metadata[$key] = $value; + } + } + + return $metadata; + } + + protected function curl_get_contents($url) { + $curl = curl_init($url); + curl_setopt($curl, CURLOPT_FAILONERROR, 1); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); + $response = curl_exec($curl); + curl_close($curl); + return $response; + } + +} diff --git a/src/Providers/OpenGraphProvider.php b/src/Providers/OpenGraphProvider.php new file mode 100644 index 0000000..7328792 --- /dev/null +++ b/src/Providers/OpenGraphProvider.php @@ -0,0 +1,29 @@ +app->bind('OpenGraph', function() { + return new \shweshi\OpenGraph\OpenGraph; + }); + } + +}