3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Read a well-formed XML file
24 * (0 => SimpleXMLElement|FALSE, 1 => errorMessage|FALSE)
26 public static function parseFile($file) {
32 if (!file_exists($file)) {
33 $error = 'File ' . $file . ' does not exist.';
36 $oldLibXMLErrors = libxml_use_internal_errors();
37 libxml_use_internal_errors(TRUE);
39 // Note that under obscure circumstances calling simplexml_load_file
40 // hit https://bugs.php.net/bug.php?id=62577
41 $string = file_get_contents($file);
42 $xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA
);
44 $error = self
::formatErrors(libxml_get_errors());
47 libxml_use_internal_errors($oldLibXMLErrors);
50 return [$xml, $error];
54 * Read a well-formed XML file
59 * (0 => SimpleXMLElement|FALSE, 1 => errorMessage|FALSE)
61 public static function parseString($string) {
67 $oldLibXMLErrors = libxml_use_internal_errors();
68 libxml_use_internal_errors(TRUE);
70 $xml = simplexml_load_string($string,
71 'SimpleXMLElement', LIBXML_NOCDATA
74 $error = self
::formatErrors(libxml_get_errors());
77 libxml_use_internal_errors($oldLibXMLErrors);
79 return [$xml, $error];
87 protected static function formatErrors($errors) {
90 foreach ($errors as $error) {
91 if ($error->level
!= LIBXML_ERR_ERROR
&& $error->level
!= LIBXML_ERR_FATAL
) {
97 $parts[] = "File=$error->file";
99 $parts[] = "Line=$error->line";
100 $parts[] = "Column=$error->column";
101 $parts[] = "Code=$error->code";
103 $messages[] = implode(" ", $parts) . ": " . trim($error->message
);
106 return implode("\n", $messages);
110 * Convert an XML element to an array.
117 public static function xmlObjToArray($obj) {
119 if (is_object($obj)) {
120 $obj = get_object_vars($obj);
122 if (is_array($obj)) {
123 foreach ($obj as $i => $v) {
124 if (is_object($v) ||
is_array($v)) {
125 $v = self
::xmlObjToArray($v);