|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace shweshi\OpenGraph; |
|
4
|
|
|
|
|
5
|
|
|
use DOMDocument; |
|
6
|
|
|
|
|
7
|
|
|
class OpenGraph |
|
8
|
|
|
{ |
|
9
|
|
|
public function fetch($url, $allMeta = null) |
|
10
|
|
|
{ |
|
11
|
|
|
$html = $this->curl_get_contents($url); |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* parsing starts here:. |
|
15
|
|
|
*/ |
|
16
|
|
|
$doc = new DOMDocument(); |
|
17
|
|
|
@$doc->loadHTML('<?xml encoding="utf-8" ?>'.$html); |
|
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
$tags = $doc->getElementsByTagName('meta'); |
|
20
|
|
|
$metadata = []; |
|
21
|
|
|
foreach ($tags as $tag) { |
|
22
|
|
|
$metaproperty = ($tag->hasAttribute('property')) ? $tag->getAttribute('property') : $tag->getAttribute('name'); |
|
23
|
|
|
if (!$allMeta && $metaproperty && strpos($tag->getAttribute('property'), 'og:') === 0) { |
|
24
|
|
|
$key = strtr(substr($metaproperty, 3), '-', '_'); |
|
25
|
|
|
$value = $tag->getAttribute('content'); |
|
26
|
|
|
} |
|
27
|
|
|
if ($allMeta && $metaproperty) { |
|
28
|
|
|
$key = (strpos($metaproperty, 'og:') === 0) ? strtr(substr($metaproperty, 3), '-', '_') : $metaproperty; |
|
29
|
|
|
$value = $tag->getAttribute('content'); |
|
30
|
|
|
} |
|
31
|
|
|
if (!empty($key)) { |
|
32
|
|
|
$metadata[$key] = $value; |
|
|
|
|
|
|
33
|
|
|
} |
|
34
|
|
|
/* |
|
35
|
|
|
* Verify image url |
|
36
|
|
|
*/ |
|
37
|
|
|
if (isset($metadata['image'])) { |
|
38
|
|
|
$isValidImageUrl = $this->verify_image_url($metadata['image']); |
|
39
|
|
|
if (!$isValidImageUrl) { |
|
40
|
|
|
$metadata['image'] = ''; |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $metadata; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
protected function curl_get_contents($url) |
|
49
|
|
|
{ |
|
50
|
|
|
$curl = curl_init($url); |
|
51
|
|
|
curl_setopt($curl, CURLOPT_FAILONERROR, 1); |
|
|
|
|
|
|
52
|
|
|
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); |
|
53
|
|
|
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); |
|
54
|
|
|
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); |
|
55
|
|
|
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); |
|
56
|
|
|
curl_setopt($curl, CURLOPT_TIMEOUT, 30); |
|
57
|
|
|
curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8'); |
|
58
|
|
|
$response = curl_exec($curl); |
|
|
|
|
|
|
59
|
|
|
curl_close($curl); |
|
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
return $response; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
protected function verify_image_url($url) |
|
65
|
|
|
{ |
|
66
|
|
|
$headers = get_headers($url); |
|
67
|
|
|
|
|
68
|
|
|
return stripos($headers[0], '200 OK') ? true : false; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: