-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElementUtils.php
More file actions
91 lines (79 loc) · 2.43 KB
/
ElementUtils.php
File metadata and controls
91 lines (79 loc) · 2.43 KB
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
<?php
/**
* Class ElementUtils.
*
* Helper class for common operations with SimpleXMLElements.
*/
class ElementUtils
{
/**
* Get attribtes from the element.
*
* @param SimpleXMLElement $element
*
* @return array
*/
public static function getAttributes(SimpleXMLElement $element)
{
$attributes = [];
foreach ($element->attributes() as $name => $value) {
$attributes[$name] = (string) $value;
}
return $attributes;
}
/**
* @param SimpleXMLElement $element
*
* @return bool
*/
public static function hasAttribute(SimpleXMLElement $element, $attributeName)
{
$attributeName = str_replace('.', '', $attributeName); //remove the dot
foreach (self::getAttributes($element) as $key => $value) {
if ($key === $attributeName) {
return true;
}
}
return false;
}
/**
* @param SimpleXMLElement $element
*
* @return string
*/
public static function getAttributeValue(SimpleXMLElement $element, $attributeName)
{
$attributeName = str_replace('.', '', $attributeName); //remove the dot
//todo: this may return the SimpleXMLElement instance!!! type to string?
return (string) $element->attributes()[$attributeName];
}
/**
* @param SimpleXMLElement[] $elements
* @param bool $generateXmlHeader
* @param string $rootElementName
*
* @return string
*/
public static function getXmlString($elements, $generateXmlHeader, $rootElementName)
{
$document = new DOMDocument('1.0', 'UTF-8');
$emptyDocumentHeader = $document->saveXML();
$document->formatOutput = true;
$rootElement = null; //either the whole document or the artificial root
if ($rootElementName !== '') {
$rootElement = $document->createElement($rootElementName);
$document->appendChild($rootElement);
} else {
$rootElement = $document;
}
foreach ($elements as $selectElement) {
$node = dom_import_simplexml($selectElement);
$rootElement->appendChild($document->importNode($node, true));
}
if ($generateXmlHeader) {
return $document->saveXML();
} else {
return str_replace($emptyDocumentHeader, '', $document->saveXML());
}
}
}