1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace rOpenDev\Google; |
4
|
|
|
|
5
|
|
|
class ExtractResults |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* @var array from \rOpenDev\Google\ResultTypes.php |
9
|
|
|
*/ |
10
|
|
|
protected $types; |
11
|
|
|
/** |
12
|
|
|
* @var object dom |
13
|
|
|
*/ |
14
|
|
|
protected $html; |
15
|
|
|
|
16
|
|
|
public function __construct(string $source) |
17
|
|
|
{ |
18
|
|
|
$this->html = new \simple_html_dom(); |
19
|
|
|
$this->html->load($source); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function getOrganicResults() |
23
|
|
|
{ |
24
|
|
|
$results = $this->html->find(str_replace(';', ', ', $this->getSelector('organic'))); |
25
|
|
|
$result = []; |
26
|
|
|
foreach ($results as $r) { |
27
|
|
|
$title = $r->find('h3, [role=heading]', 0); |
28
|
|
|
if ($title) { |
29
|
|
|
$result[] = [ |
30
|
|
|
'type' => 'organic', |
31
|
|
|
'title' => $this->normalizeTextFromGoogle($title->innertext), |
32
|
|
|
'link' => $this->getUrlFromGoogleSerpFromat($r->find('a', 0)->href), |
33
|
|
|
]; |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $result; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return string or NULL if next page link not found |
42
|
|
|
*/ |
43
|
|
|
public function getNextPageLink() |
44
|
|
|
{ |
45
|
|
|
if (isset($this->html->find('#pnnext, h3 > a[href]')[0])) { |
46
|
|
|
return $this->html->find('#pnnext')[0]->href; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function getSelector(string $type) |
51
|
|
|
{ |
52
|
|
|
if (null === $this->types) { |
53
|
|
|
$this->types = ResultsTypes::get(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $this->types[$type]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
protected static function getUrlFromGoogleSerpFromat($str) |
60
|
|
|
{ |
61
|
|
|
preg_match('/\/url\?.*(q|url)=(http.+)&/SiU', $str, $m1); |
62
|
|
|
$str = isset($m1[2]) ? $m1[2] : $str; |
63
|
|
|
|
64
|
|
|
return $str; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected function normalizeTextFromGoogle($text) |
68
|
|
|
{ |
69
|
|
|
return htmlspecialchars_decode(html_entity_decode(strip_tags($text))); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|