1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file contains additional helper methods. |
4
|
|
|
*/ |
5
|
|
|
namespace Danmichaelo\QuiteSimpleXMLElement; |
6
|
|
|
|
7
|
|
|
use SimpleXMLElement; |
8
|
|
|
|
9
|
|
|
class QuiteSimpleXMLElement extends SimpleXMLElementWrapper |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var SimpleXMLElement |
13
|
|
|
*/ |
14
|
|
|
public $el; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Get a node attribute value. |
18
|
|
|
* |
19
|
|
|
* @param string $attribute |
20
|
|
|
* @return string |
21
|
|
|
*/ |
22
|
|
|
public function attr($attribute) |
23
|
|
|
{ |
24
|
|
|
return trim((string) $this->el->attributes()->{$attribute}); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Get the first node matching an XPath query, or null if no match. |
29
|
|
|
* |
30
|
|
|
* @param string $path |
31
|
|
|
* @return QuiteSimpleXMLElement |
32
|
|
|
*/ |
33
|
|
|
public function first($path) |
34
|
|
|
{ |
35
|
|
|
// Convenience method |
36
|
|
|
$x = $this->xpath($path); |
37
|
|
|
|
38
|
|
|
return count($x) ? $x[0] : null; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Check if the document has at least one node matching an XPath query. |
43
|
|
|
* |
44
|
|
|
* @param string $path |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
|
|
public function has($path) |
48
|
|
|
{ |
49
|
|
|
$x = $this->xpath($path); |
50
|
|
|
|
51
|
|
|
return count($x) ? true : false; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Get all nodes matching an XPath query. |
56
|
|
|
* |
57
|
|
|
* @param string $path |
58
|
|
|
* @return QuiteSimpleXMLElement[] |
59
|
|
|
*/ |
60
|
|
|
public function xpath($path) |
61
|
|
|
{ |
62
|
|
|
return array_map(function ($el) { |
63
|
|
|
return new QuiteSimpleXMLElement($el, $this); |
64
|
|
|
}, $this->el->xpath($path)); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Alias for `xpath()`. |
69
|
|
|
* |
70
|
|
|
* @param $path |
71
|
|
|
* @return QuiteSimpleXMLElement[] |
72
|
|
|
*/ |
73
|
|
|
public function all($path) |
74
|
|
|
{ |
75
|
|
|
return $this->xpath($path); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Get the text of the first node matching an XPath query. By default, |
80
|
|
|
* the text will be trimmed, but if you want the untrimmed text, set |
81
|
|
|
* the second paramter to False. |
82
|
|
|
* |
83
|
|
|
* @param string $path |
84
|
|
|
* @param bool $trim |
85
|
|
|
* @return string |
86
|
|
|
*/ |
87
|
|
|
public function text($path='.', $trim=true) |
88
|
|
|
{ |
89
|
|
|
$text = strval($this->first($path)); |
90
|
|
|
|
91
|
|
|
return $trim ? trim($text) : $text; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|