|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace shweshi\OpenGraph; |
| 4 | + |
| 5 | +use DOMDocument; |
| 6 | + |
| 7 | +class OpenGraph { |
| 8 | + |
| 9 | + public function fetch($url) { |
| 10 | + $html = $this->curl_get_contents($url); |
| 11 | + |
| 12 | + /** |
| 13 | + * parsing starts here: |
| 14 | + */ |
| 15 | + $doc = new DOMDocument(); |
| 16 | + @$doc->loadHTML($html); |
| 17 | + |
| 18 | + |
| 19 | + $tags = $doc->getElementsByTagName('meta'); |
| 20 | + $metadata = array(); |
| 21 | + |
| 22 | + foreach ($tags as $tag) { |
| 23 | + if ($tag->hasAttribute('property') && strpos($tag->getAttribute('property'), 'og:') === 0) { |
| 24 | + $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_'); |
| 25 | + $value = $tag->getAttribute('content'); |
| 26 | + } |
| 27 | + if (!empty($key)) { |
| 28 | + $metadata[$key] = $value; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return $metadata; |
| 33 | + } |
| 34 | + |
| 35 | + protected function curl_get_contents($url) { |
| 36 | + $curl = curl_init($url); |
| 37 | + curl_setopt($curl, CURLOPT_FAILONERROR, 1); |
| 38 | + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); |
| 39 | + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); |
| 40 | + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); |
| 41 | + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); |
| 42 | + curl_setopt($curl, CURLOPT_TIMEOUT, 30); |
| 43 | + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); |
| 44 | + $response = curl_exec($curl); |
| 45 | + curl_close($curl); |
| 46 | + return $response; |
| 47 | + } |
| 48 | + |
| 49 | +} |
0 commit comments