-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmllib.php
75 lines (70 loc) · 3.29 KB
/
xmllib.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
69
70
71
72
73
74
75
<?php
/**
* A general library for XML related things.
*
*
* @package mod-project
* @category mod
* @author Yann Ducruy (yann[dot]ducruy[at]gmail[dot]com). Contact me if needed
* @date 12/06/2015
* @version 3.2
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*
*/
if (!function_exists('recordstoxml')){
/**
* recordstoxml : takes an array of records and transforms it to xml structure.
* keys are converted. When an associative array is found, keys are used as element id.
* Note that any HTML tagged content makes the value being escaped in a <![CDATA[ ]]> section
* for XSLT escaping.
*
* When an object is found, properties of the object are converted into inner elements
* @param array $array
* @param string $baseelement the base element
* @param string $subrecords if there are subrecords elements to include as child tree, they are available as an XML formated string
* @param boolean $withheader if true, adds a standard XML document header
* @param boolean $translate if true, all fields value are passed thru the get_string() translating call
* @param string $stylesheet may mention a stylesheet call to the document header, if header is enabled
* @return a string XML formatted, with or without XML heading entity
*/
function recordstoxml(&$array, $baseelement, $subrecords = '', $withheader=true, $translate=false, $stylesheet = ''){
global $strings;
$baseelement = strtolower($baseelement); // calibrates the base name
$xml = ($withheader) ? "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n{$stylesheet}\n<rootnode>\n" : '' ;
$xml .= "<{$baseelement}s>\n";
$ix = 1;
if (!empty($array)){
foreach($array as $key => $element){
if (is_object($element)){
$fields = get_object_vars($element);
$xml .= "\t<{$baseelement} id=\"$key\">\n";
$xml .= "\t\t<ix>$ix</ix>\n";
foreach($fields as $fieldname => $fieldvalue){
$translation = $fieldvalue;
if (is_string($fieldvalue)){
// $translation = get_string($fieldvalue, $translate);
}
if ($translate && !preg_match('/\[\['.preg_quote($fieldvalue).'\]\]/', $translation)){
$fieldvalue = $translation;
}
if (preg_match("/<|>/", $fieldvalue)){
$xml .= "\t\t<{$fieldname}><![CDATA[ ".str_replace("& ", "& ", $fieldvalue)." ]]></{$fieldname}>\n";
}
else{
$xml .= "\t\t<{$fieldname}>".str_replace("& ", "& ", $fieldvalue)."</{$fieldname}>\n";
}
}
$xml .= "\t</{$baseelement}>\n";
}
$ix++;
}
$subrecords = "\t" . str_replace("\n", "\n\t", $subrecords); // give one indent more
$subrecords = substr($subrecords, 0, strlen($subrecords) -1); // chops last \t
$xml .= $subrecords;
}
$xml .= "</{$baseelement}s>\n";
$xml .= ($withheader) ? "</rootnode>\n" : '' ;
return $xml;
}
}
?>