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