-
Notifications
You must be signed in to change notification settings - Fork 0
/
Xml.php
68 lines (63 loc) · 2.05 KB
/
Xml.php
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
<?php namespace Mreschke\Helpers;
use DomDocument;
use SimpleXMLElement;
/**
* Xml helpers
* @copyright 2017 Matthew Reschke
* @license http://mreschke.com/license/mit
* @author Matthew Reschke <mail@mreschke.com>
*/
class Xml
{
/**
* Return pretty printed (structured) string of this SimpleXMLElement
* @param SimpleXMLElement $xml
* @return string
*/
public static function prettyPrint($xml)
{
// Load string into DomDocument to apply formatting
$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($xml->saveXML());
// Return formatted XML as string
return $doc->saveXML();
}
/**
* Append one SimpleXMLElement to another
* @param SimpleXMLElement &$simpleXmlMain this is the main element
* @param SimpleXMLElement &$simpleXmlAppend append this to main
* @return void (no return, all ByRef)
*/
public static function appendElement(&$simpleXmlMain, &$simpleXmlAppend)
{
// Ignore if any are empty
if (!isset($simpleXmlMain) || !isset($simpleXmlAppend)) return;
foreach ($simpleXmlAppend->children() as $child) {
$temp = $simpleXmlMain->addChild($child->getName(), (string) htmlentities($child));
foreach ($child->attributes() as $attr_key => $attr_value) {
$temp->addAttribute($attr_key, $attr_value);
}
// Recursively add each childs children
Xml::appendElement($temp, $child);
}
}
/**
* Save one SimpleXMLElement to file
* @param SimpleXMLElement $xml
* @param string $file
* @param boolean $prettyPrint = false
* @return void
*/
public static function save(SimpleXMLElement $xml, $file, $prettyPrint = false)
{
if ($prettyPrint) {
// Pretty print
file_put_contents($file, Xml::prettyPrint($xml));
} else {
// No formatting
file_put_contents($file, $xml->saveXML());
}
}
}