blob: 9beb59c16f697214ed83c88293b7d08808f88c04 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
<?php
namespace PicoFeed\Scraper;
use DOMXPath;
use PicoFeed\Parser\XmlParser;
/**
* Rule Parser.
*
* @author Frederic Guillot
*/
class RuleParser implements ParserInterface
{
private $dom;
private $xpath;
private $rules = array();
/**
* Constructor.
*
* @param string $html
* @param array $rules
*/
public function __construct($html, array $rules)
{
$this->rules = $rules;
$this->dom = XmlParser::getHtmlDocument('<?xml version="1.0" encoding="UTF-8">'.$html);
$this->xpath = new DOMXPath($this->dom);
}
/**
* Get the relevant content with predefined rules.
*
* @return string
*/
public function execute()
{
$this->stripTags();
return $this->findContent();
}
/**
* Remove HTML tags.
*/
public function stripTags()
{
if (isset($this->rules['strip']) && is_array($this->rules['strip'])) {
foreach ($this->rules['strip'] as $pattern) {
$nodes = $this->xpath->query($pattern);
if ($nodes !== false && $nodes->length > 0) {
foreach ($nodes as $node) {
$node->parentNode->removeChild($node);
}
}
}
}
}
/**
* Fetch content based on Xpath rules.
*/
public function findContent()
{
$content = '';
if (isset($this->rules['body']) && is_array($this->rules['body'])) {
foreach ($this->rules['body'] as $pattern) {
$nodes = $this->xpath->query($pattern);
if ($nodes !== false && $nodes->length > 0) {
foreach ($nodes as $node) {
$content .= $this->dom->saveXML($node);
}
}
}
}
return $content;
}
/**
* Fetch next link based on Xpath rules.
*
* @return string
*/
public function findNextLink()
{
if (isset($this->rules['next_page']) && is_array($this->rules['next_page'])) {
foreach ($this->rules['next_page'] as $pattern) {
$nodes = $this->xpath->query($pattern);
if ($nodes !== false && $nodes->length > 0) {
foreach ($nodes as $node) {
return $node->getAttribute('href');
}
}
}
}
return null;
}
}
|