protected function arrayToXML($fieldInfo, SimpleXMLElement $xmlFieldInfo) { foreach ($fieldInfo as $treeItemSID => $treeItemInfo) { $branch = $xmlFieldInfo->addChild('branch'); $branch->addChild('sid', $treeItemSID); $branch->addChild('caption', XML_Util::replaceEntities($treeItemInfo['caption'])); if (!empty($treeItemInfo['items'])) { $branchItems = $branch->addChild('items'); $this->arrayToXML($treeItemInfo['items'], $branchItems); } } }
* several examples for the methods of XML_Util * * $Id: example.php,v 1.12 2004/12/23 13:22:00 schst Exp $ * * @author Stephan Schmidt * @package XML_Util * @subpackage examples * @category XML */ error_reporting(E_ALL); require_once 'XML/Util.php'; /** * replacing XML entities */ print "replace XML entities:<br>\n"; print XML_Util::replaceEntities("This string contains < & >."); print "\n<br><br>\n"; /** * reversing XML entities */ print "replace XML entities:<br>\n"; print XML_Util::reverseEntities("This string contains < & >."); print "\n<br><br>\n"; /** * building XML declaration */ print "building XML declaration:<br>\n"; print htmlspecialchars(XML_Util::getXMLDeclaration()); print "\n<br><br>\n"; print "building XML declaration with additional attributes:<br>"; print htmlspecialchars(XML_Util::getXMLDeclaration("1.0", "UTF-8", true));
/** * serialize a token * * This method does the actual beautifying. * * @param array $token structure that should be serialized * * @return mixed * @access private * @todo split this method into smaller methods */ function _serializeToken($token) { switch ($token["type"]) { /* * serialize XML Element */ case XML_BEAUTIFIER_ELEMENT: $indent = $this->_getIndentString($token["depth"]); // adjust tag case if ($this->_options["caseFolding"] === true) { switch ($this->_options["caseFoldingTo"]) { case "uppercase": $token["tagname"] = strtoupper($token["tagname"]); $token["attribs"] = array_change_key_case($token["attribs"], CASE_UPPER); break; case "lowercase": $token["tagname"] = strtolower($token["tagname"]); $token["attribs"] = array_change_key_case($token["attribs"], CASE_LOWER); break; } } if ($this->_options["multilineTags"] == true) { $attIndent = $indent . str_repeat(" ", 2 + strlen($token["tagname"])); } else { $attIndent = null; } // check for children switch ($token["contains"]) { // contains only CData or is empty case XML_BEAUTIFIER_CDATA: case XML_BEAUTIFIER_EMPTY: if (sizeof($token["children"]) >= 1) { $data = $token["children"][0]["data"]; } else { $data = ''; } if (strstr($data, "\n")) { $data = "\n" . $this->_indentTextBlock($data, $token['depth'] + 1, true); } $xml = $indent . XML_Util::createTag($token["tagname"], $token["attribs"], $data, null, XML_UTIL_REPLACE_ENTITIES, $this->_options["multilineTags"], $attIndent) . $this->_options["linebreak"]; break; // contains mixed content // contains mixed content default: $xml = $indent . XML_Util::createStartElement($token["tagname"], $token["attribs"], null, $this->_options["multilineTags"], $attIndent) . $this->_options["linebreak"]; $cnt = count($token["children"]); for ($i = 0; $i < $cnt; $i++) { $xml .= $this->_serializeToken($token["children"][$i]); } $xml .= $indent . XML_Util::createEndElement($token["tagname"]) . $this->_options["linebreak"]; break; break; } break; /* * serialize CData */ /* * serialize CData */ case XML_BEAUTIFIER_CDATA: if ($token["depth"] > 0) { $xml = str_repeat($this->_options["indent"], $token["depth"]); } else { $xml = ""; } $xml .= XML_Util::replaceEntities($token["data"]) . $this->_options["linebreak"]; break; /* * serialize CData section */ /* * serialize CData section */ case XML_BEAUTIFIER_CDATA_SECTION: if ($token["depth"] > 0) { $xml = str_repeat($this->_options["indent"], $token["depth"]); } else { $xml = ""; } $xml .= '<![CDATA[' . $token["data"] . ']]>' . $this->_options["linebreak"]; break; /* * serialize entity */ /* * serialize entity */ case XML_BEAUTIFIER_ENTITY: if ($token["depth"] > 0) { $xml = str_repeat($this->_options["indent"], $token["depth"]); } else { $xml = ""; } $xml .= "&" . $token["name"] . ";" . $this->_options["linebreak"]; break; /* * serialize Processing instruction */ /* * serialize Processing instruction */ case XML_BEAUTIFIER_PI: $indent = $this->_getIndentString($token["depth"]); $xml = $indent . "<?" . $token["target"] . $this->_options["linebreak"] . $this->_indentTextBlock(rtrim($token["data"]), $token["depth"]) . $indent . "?>" . $this->_options["linebreak"]; break; /* * comments */ /* * comments */ case XML_BEAUTIFIER_COMMENT: $lines = count(explode("\n", $token["data"])); /* * normalize comment, i.e. combine it to one * line and remove whitespace */ if ($this->_options["normalizeComments"] && $lines > 1) { $comment = preg_replace("/\\s\\s+/s", " ", str_replace("\n", " ", $token["data"])); $lines = 1; } else { $comment = $token["data"]; } /* * check for the maximum length of one line */ if ($this->_options["maxCommentLine"] > 0) { if ($lines > 1) { $commentLines = explode("\n", $comment); } else { $commentLines = array($comment); } $comment = ""; for ($i = 0; $i < $lines; $i++) { if (strlen($commentLines[$i]) <= $this->_options["maxCommentLine"]) { $comment .= $commentLines[$i]; continue; } $comment .= wordwrap($commentLines[$i], $this->_options["maxCommentLine"]); if ($i != $lines - 1) { $comment .= "\n"; } } $lines = count(explode("\n", $comment)); } $indent = $this->_getIndentString($token["depth"]); if ($lines > 1) { $xml = $indent . "<!--" . $this->_options["linebreak"] . $this->_indentTextBlock($comment, $token["depth"] + 1, true) . $indent . "-->" . $this->_options["linebreak"]; } else { $xml = $indent . sprintf("<!-- %s -->", trim($comment)) . $this->_options["linebreak"]; } break; /* * xml declaration */ /* * xml declaration */ case XML_BEAUTIFIER_XML_DECLARATION: $indent = $this->_getIndentString($token["depth"]); $xml = $indent . XML_Util::getXMLDeclaration($token["version"], $token["encoding"], $token["standalone"]); break; /* * xml declaration */ /* * xml declaration */ case XML_BEAUTIFIER_DT_DECLARATION: $xml = $token["data"]; break; /* * all other elements */ /* * all other elements */ case XML_BEAUTIFIER_DEFAULT: default: $xml = XML_Util::replaceEntities($token["data"]); break; } return $xml; }
/** * create a tag from an array * this method awaits an array in the following format * <pre> * array( * "qname" => $qname // qualified name of the tag * "namespace" => $namespace // namespace prefix (optional, if qname is specified or no namespace) * "localpart" => $localpart, // local part of the tagname (optional, if qname is specified) * "attributes" => array(), // array containing all attributes (optional) * "content" => $content, // tag content (optional) * "namespaceUri" => $namespaceUri // namespaceUri for the given namespace (optional) * ) * </pre> * * <code> * require_once 'XML/Util.php'; * * $tag = array( * "qname" => "foo:bar", * "namespaceUri" => "http://foo.com", * "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), * "content" => "I'm inside the tag", * ); * // creating a tag with qualified name and namespaceUri * $string = XML_Util::createTagFromArray($tag); * </code> * * @access public * @static * @param array $tag tag definition * @param integer $replaceEntities whether to replace XML special chars in content, embedd it in a CData section or none of both * @param boolean $multiline whether to create a multiline tag where each attribute gets written to a single line * @param string $indent string used to indent attributes (_auto indents attributes so they start at the same column) * @param string $linebreak string used for linebreaks * @return string $string XML tag * @see XML_Util::createTag() * @uses XML_Util::attributesToString() to serialize the attributes of the tag * @uses XML_Util::splitQualifiedName() to get local part and namespace of a qualified name */ function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = "_auto", $linebreak = "\n", $encoding = XML_UTIL_ENTITIES_XML) { if (isset($tag["content"]) && !is_scalar($tag["content"])) { return XML_Util::raiseError("Supplied non-scalar value as tag content", XML_UTIL_ERROR_NON_SCALAR_CONTENT); } if (!isset($tag['qname']) && !isset($tag['localPart'])) { return XML_Util::raiseError('You must either supply a qualified name (qname) or local tag name (localPart).', XML_UTIL_ERROR_NO_TAG_NAME); } // if no attributes hav been set, use empty attributes if (!isset($tag["attributes"]) || !is_array($tag["attributes"])) { $tag["attributes"] = array(); } // qualified name is not given if (!isset($tag["qname"])) { // check for namespace if (isset($tag["namespace"]) && !empty($tag["namespace"])) { $tag["qname"] = $tag["namespace"] . ":" . $tag["localPart"]; } else { $tag["qname"] = $tag["localPart"]; } // namespace URI is set, but no namespace } elseif (isset($tag["namespaceUri"]) && !isset($tag["namespace"])) { $parts = XML_Util::splitQualifiedName($tag["qname"]); $tag["localPart"] = $parts["localPart"]; if (isset($parts["namespace"])) { $tag["namespace"] = $parts["namespace"]; } } if (isset($tag["namespaceUri"]) && !empty($tag["namespaceUri"])) { // is a namespace given if (isset($tag["namespace"]) && !empty($tag["namespace"])) { $tag["attributes"]["xmlns:" . $tag["namespace"]] = $tag["namespaceUri"]; } else { // define this Uri as the default namespace $tag["attributes"]["xmlns"] = $tag["namespaceUri"]; } } // check for multiline attributes if ($multiline === true) { if ($indent === "_auto") { $indent = str_repeat(" ", strlen($tag["qname"]) + 2); } } // create attribute list $attList = XML_Util::attributesToString($tag["attributes"], true, $multiline, $indent, $linebreak); if (!isset($tag["content"]) || (string) $tag["content"] == '') { $tag = sprintf("<%s%s />", $tag["qname"], $attList); } else { if ($replaceEntities == XML_UTIL_REPLACE_ENTITIES) { $tag["content"] = XML_Util::replaceEntities($tag["content"], $encoding); } elseif ($replaceEntities == XML_UTIL_CDATA_SECTION) { $tag["content"] = XML_Util::createCDataSection($tag["content"]); } $tag = sprintf("<%s%s>%s</%s>", $tag["qname"], $attList, $tag["content"], $tag["qname"]); } return $tag; }
/** * create a tag from an array * this method awaits an array in the following format * <pre> * array( * // qualified name of the tag * 'qname' => $qname * * // namespace prefix (optional, if qname is specified or no namespace) * 'namespace' => $namespace * * // local part of the tagname (optional, if qname is specified) * 'localpart' => $localpart, * * // array containing all attributes (optional) * 'attributes' => array(), * * // tag content (optional) * 'content' => $content, * * // namespaceUri for the given namespace (optional) * 'namespaceUri' => $namespaceUri * ) * </pre> * * <code> * require_once 'XML/Util.php'; * * $tag = array( * 'qname' => 'foo:bar', * 'namespaceUri' => 'http://foo.com', * 'attributes' => array('key' => 'value', 'argh' => 'fruit&vegetable'), * 'content' => 'I\'m inside the tag', * ); * // creating a tag with qualified name and namespaceUri * $string = XML_Util::createTagFromArray($tag); * </code> * * @param array $tag tag definition * @param int $replaceEntities whether to replace XML special chars in * content, embedd it in a CData section * or none of both * @param bool $multiline whether to create a multiline tag where each * attribute gets written to a single line * @param string $indent string used to indent attributes * (_auto indents attributes so they start * at the same column) * @param string $linebreak string used for linebreaks * @param bool $sortAttributes Whether to sort the attributes or not * * @return string XML tag * @access public * @static * @see createTag() * @uses attributesToString() to serialize the attributes of the tag * @uses splitQualifiedName() to get local part and namespace of a qualified name * @uses createCDataSection() * @uses raiseError() */ function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true) { if (isset($tag['content']) && !is_scalar($tag['content'])) { return XML_Util::raiseError('Supplied non-scalar value as tag content', XML_UTIL_ERROR_NON_SCALAR_CONTENT); } if (!isset($tag['qname']) && !isset($tag['localPart'])) { return XML_Util::raiseError('You must either supply a qualified name ' . '(qname) or local tag name (localPart).', XML_UTIL_ERROR_NO_TAG_NAME); } // if no attributes hav been set, use empty attributes if (!isset($tag['attributes']) || !is_array($tag['attributes'])) { $tag['attributes'] = array(); } if (isset($tag['namespaces'])) { foreach ($tag['namespaces'] as $ns => $uri) { $tag['attributes']['xmlns:' . $ns] = $uri; } } if (!isset($tag['qname'])) { // qualified name is not given // check for namespace if (isset($tag['namespace']) && !empty($tag['namespace'])) { $tag['qname'] = $tag['namespace'] . ':' . $tag['localPart']; } else { $tag['qname'] = $tag['localPart']; } } elseif (isset($tag['namespaceUri']) && !isset($tag['namespace'])) { // namespace URI is set, but no namespace $parts = XML_Util::splitQualifiedName($tag['qname']); $tag['localPart'] = $parts['localPart']; if (isset($parts['namespace'])) { $tag['namespace'] = $parts['namespace']; } } if (isset($tag['namespaceUri']) && !empty($tag['namespaceUri'])) { // is a namespace given if (isset($tag['namespace']) && !empty($tag['namespace'])) { $tag['attributes']['xmlns:' . $tag['namespace']] = $tag['namespaceUri']; } else { // define this Uri as the default namespace $tag['attributes']['xmlns'] = $tag['namespaceUri']; } } // check for multiline attributes if ($multiline === true) { if ($indent === '_auto') { $indent = str_repeat(' ', strlen($tag['qname']) + 2); } } // create attribute list $attList = XML_Util::attributesToString($tag['attributes'], $sortAttributes, $multiline, $indent, $linebreak, $replaceEntities); if (!isset($tag['content']) || (string) $tag['content'] == '') { $tag = sprintf('<%s%s />', $tag['qname'], $attList); } else { switch ($replaceEntities) { case XML_UTIL_ENTITIES_NONE: break; case XML_UTIL_CDATA_SECTION: $tag['content'] = XML_Util::createCDataSection($tag['content']); break; default: $tag['content'] = XML_Util::replaceEntities($tag['content'], $replaceEntities); break; } $tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'], $tag['qname']); } return $tag; }
/** * create a tag from an array * this method awaits an array in the following format * array( * 'qname' => $tagName, * 'attributes' => array(), * 'content' => $content, // optional * 'namespace' => $namespace // optional * 'namespaceUri' => $namespaceUri // optional * ) * * @param array $tag tag definition * @param boolean $firstCall whether or not this is the first call * * @return string $string XML tag * @access private */ function _createXMLTag($tag, $firstCall = true) { // build fully qualified tag name if ($this->options[XML_SERIALIZER_OPTION_NAMESPACE] !== null) { if (is_array($this->options[XML_SERIALIZER_OPTION_NAMESPACE])) { $tag['qname'] = $this->options[XML_SERIALIZER_OPTION_NAMESPACE][0] . ':' . $tag['qname']; } else { $tag['qname'] = $this->options[XML_SERIALIZER_OPTION_NAMESPACE] . ':' . $tag['qname']; } } // attribute indentation if ($this->options[XML_SERIALIZER_OPTION_INDENT_ATTRIBUTES] !== false) { $multiline = true; $indent = str_repeat($this->options[XML_SERIALIZER_OPTION_INDENT], $this->_tagDepth); if ($this->options[XML_SERIALIZER_OPTION_INDENT_ATTRIBUTES] == '_auto') { $indent .= str_repeat(' ', strlen($tag['qname']) + 2); } else { $indent .= $this->options[XML_SERIALIZER_OPTION_INDENT_ATTRIBUTES]; } } else { $multiline = false; $indent = false; } if (is_array($tag['content'])) { if (empty($tag['content'])) { $tag['content'] = ''; } } elseif (XML_SERIALIZER_OPTION_FALSE_AS_STRING && $tag['content'] === false) { $tag['content'] = '0'; } elseif (is_scalar($tag['content']) && (string) $tag['content'] == '') { $tag['content'] = ''; } // replace XML entities if ($firstCall === true) { if ($this->options[XML_SERIALIZER_OPTION_CDATA_SECTIONS] === true) { $replaceEntities = XML_UTIL_CDATA_SECTION; } else { $replaceEntities = $this->options[XML_SERIALIZER_OPTION_ENTITIES]; } } else { // this is a nested call, so value is already encoded // and must not be encoded again $replaceEntities = XML_SERIALIZER_ENTITIES_NONE; // but attributes need to be encoded anyways // (done here because the rest of the code assumes the same encoding // can be used both for attributes and content) foreach ($tag['attributes'] as $k => $v) { $v = XML_Util::replaceEntities($v, $this->options[XML_SERIALIZER_OPTION_ENTITIES]); $tag['attributes'][$k] = $v; } } if (is_scalar($tag['content']) || is_null($tag['content'])) { if ($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC]) { if ($firstCall === true) { $tag['content'] = call_user_func($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC], $tag['content']); } $tag['attributes'] = array_map($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC], $tag['attributes']); } $tag = XML_Util::createTagFromArray($tag, $replaceEntities, $multiline, $indent, $this->options[XML_SERIALIZER_OPTION_LINEBREAKS]); } elseif (is_array($tag['content'])) { $tag = $this->_serializeArray($tag['content'], $tag['qname'], $tag['attributes']); } elseif (is_object($tag['content'])) { $tag = $this->_serializeObject($tag['content'], $tag['qname'], $tag['attributes']); } elseif (is_resource($tag['content'])) { settype($tag['content'], 'string'); if ($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC]) { if ($replaceEntities === true) { $tag['content'] = call_user_func($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC], $tag['content']); } $tag['attributes'] = array_map($this->options[XML_SERIALIZER_OPTION_ENCODE_FUNC], $tag['attributes']); } $tag = XML_Util::createTagFromArray($tag, $replaceEntities); } return $tag; }
/** * Serialize and save the updated tranlation data to the XML file * * @return boolean | PEAR_Error * @access private * @see Translation2_Admin_Container_xml::_scheduleSaving() */ function _saveData() { if ($this->options['save_on_shutdown']) { $data =& $this->_data; } else { $data = $this->_data; } $this->_convertEncodings('to_xml', $data); $this->_convertLangEncodings('to_xml', $data); // Serializing $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n" . "<!DOCTYPE translation2 [\n" . TRANSLATION2_DTD . "]>\n\n" . "<translation2>\n" . " <languages>\n"; foreach ($data['languages'] as $lang => $spec) { extract($spec); $xml .= " <lang id=\"{$lang}\">\n" . " <name>" . ($name ? ' ' . XML_Util::replaceEntities($name) . ' ' : '') . "</name>\n" . " <meta>" . ($meta ? ' ' . XML_Util::replaceEntities($meta) . ' ' : "") . "</meta>\n" . " <error_text>" . ($error_text ? ' ' . XML_Util::replaceEntities($error_text) . ' ' : "") . "</error_text>\n" . " <encoding>" . ($encoding ? " {$encoding} " : "") . "</encoding>\n" . " </lang>\n"; } $xml .= " </languages>\n" . " <pages>\n"; foreach ($data['pages'] as $page => $strings) { $xml .= " <page key=\"" . XML_Util::replaceEntities($page) . "\">\n"; foreach ($strings as $str_id => $translations) { $xml .= " <string key=\"" . XML_Util::replaceEntities($str_id) . "\">\n"; foreach ($translations as $lang => $str) { $xml .= " <tr lang=\"{$lang}\"> " . XML_Util::replaceEntities($str) . " </tr>\n"; } $xml .= " </string>\n"; } $xml .= " </page>\n"; } $xml .= " </pages>\n" . "</translation2>\n"; unset($data); // Saving if (!($f = fopen($this->_filename, 'w'))) { return $this->raiseError(sprintf('Unable to open the XML file ("%s") for writing', $this->_filename), TRANSLATION2_ERROR_CANNOT_WRITE_FILE, PEAR_ERROR_TRIGGER, E_USER_ERROR); } @flock($f, LOCK_EX); fwrite($f, $xml); //@flock($f, LOCK_UN); fclose($f); return true; }
/** * @param array $data * @return string */ protected function generateXMLData($data) { $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n" . "<!DOCTYPE translation2 [\n" . TRANSLATION2_DTD . "]>\n\n" . "<translation2>\n" . " <languages>\n"; foreach ($data['languages'] as $lang => $spec) { extract($spec); $xml .= " <lang id=\"{$lang}\">\n" . " <name>" . ($name ? ' ' . XML_Util::replaceEntities($name) . ' ' : '') . "</name>\n" . " <meta>" . ($meta ? ' ' . str_replace('__quote__', '"', XML_Util::replaceEntities(str_replace('"', "__quote__", $meta))) . ' ' : "") . "</meta>\n" . " <error_text>" . ($error_text ? ' ' . XML_Util::replaceEntities($error_text) . ' ' : "") . "</error_text>\n" . " <encoding>" . ($encoding ? " {$encoding} " : "") . "</encoding>\n" . " </lang>\n"; } $xml .= " </languages>\n" . " <pages>\n"; foreach ($data['pages'] as $page => $strings) { $xml .= " <page key=\"" . XML_Util::replaceEntities($page) . "\">\n"; foreach ($strings as $str_id => $translations) { $xml .= " <string key=\"" . XML_Util::replaceEntities($str_id) . "\">\n"; foreach ($translations as $lang => $str) { $xml .= " <tr lang=\"{$lang}\"> " . XML_Util::replaceEntities($str) . " </tr>\n"; } $xml .= " </string>\n"; } $xml .= " </page>\n"; } $xml .= " </pages>\n" . "</translation2>\n"; return $xml; }
/** * @param array $data * @return bool|PEAR_Error|void */ private function _saveDataPages($data) { $fileName = !empty($this->options['filename_pages']) ? $this->options['filename_pages'] : false; if (!$fileName) { return false; } $this->_convertEncodings('to_xml', $data); // Serializing $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n" . "<!DOCTYPE translation2 [\n" . TRANSLATION2_DTD_PAGES . "]>\n\n" . "<translation2>\n" . " <languages>\n"; foreach ($data['languages'] as $lang => $spec) { extract($spec); $xml .= " <lang id=\"{$lang}\"/>\n"; } $xml .= " </languages>\n" . " <pages>\n"; foreach ($data['pages'] as $page => $strings) { $xml .= " <page key=\"" . XML_Util::replaceEntities($page) . "\">\n"; foreach ($strings as $str_id => $translations) { $xml .= " <string key=\"" . XML_Util::replaceEntities($str_id) . "\">\n"; foreach ($translations as $lang => $str) { $xml .= " <tr lang=\"{$lang}\"> " . XML_Util::replaceEntities($str) . " </tr>\n"; } $xml .= " </string>\n"; } $xml .= " </page>\n"; } $xml .= " </pages>\n" . "</translation2>\n"; unset($data); // Saving if (!($f = fopen($fileName, 'w'))) { return $this->raiseError(sprintf('Unable to open the XML file ("%s") for writing', $fileName), TRANSLATION2_ERROR_CANNOT_WRITE_FILE, PEAR_ERROR_TRIGGER, E_USER_ERROR); } @flock($f, LOCK_EX); fwrite($f, $xml); //@flock($f, LOCK_UN); fclose($f); }
/** * serialize an array * * @param array &$array array to serialize * @param string $tagName name of the root tag * @param array $attributes attributes for the root tag * * @return string $string serialized data * @access private * @uses XML_Util::isValidName() to check, whether key has to be substituted * @uses XML_Util::replaceEntities() * @uses XML_Util::createComment() * @uses PEAR::popExpect() * @uses PEAR::expectError() */ function _serializeArray(&$array, $tagName = null, $attributes = array()) { $_content = null; $_comment = null; // check for comment if ($this->options[XML_SERIALIZER_OPTION_COMMENT_KEY] !== null) { if (isset($array[$this->options[XML_SERIALIZER_OPTION_COMMENT_KEY]])) { $_comment = $array[$this->options[XML_SERIALIZER_OPTION_COMMENT_KEY]]; unset($array[$this->options[XML_SERIALIZER_OPTION_COMMENT_KEY]]); } } /** * check for special attributes */ if ($this->options[XML_SERIALIZER_OPTION_ATTRIBUTES_KEY] !== null) { if (isset($array[$this->options[XML_SERIALIZER_OPTION_ATTRIBUTES_KEY]])) { $attributes = $array[$this->options[XML_SERIALIZER_OPTION_ATTRIBUTES_KEY]]; unset($array[$this->options[XML_SERIALIZER_OPTION_ATTRIBUTES_KEY]]); } /** * check for special content */ if ($this->options[XML_SERIALIZER_OPTION_CONTENT_KEY] !== null) { if (isset($array[$this->options[XML_SERIALIZER_OPTION_CONTENT_KEY]])) { $_content = XML_Util::replaceEntities($array[$this->options[XML_SERIALIZER_OPTION_CONTENT_KEY]]); unset($array[$this->options[XML_SERIALIZER_OPTION_CONTENT_KEY]]); } } } if ($this->options[XML_SERIALIZER_OPTION_IGNORE_NULL] === true) { foreach (array_keys($array) as $key) { if (is_null($array[$key])) { unset($array[$key]); } } } /* * if mode is set to simpleXML, check whether * the array is associative or indexed */ if (is_array($array) && !empty($array) && $this->options[XML_SERIALIZER_OPTION_MODE] == XML_SERIALIZER_MODE_SIMPLEXML) { $indexed = true; foreach ($array as $key => $val) { if (!is_int($key)) { $indexed = false; break; } } if ($indexed && $this->options[XML_SERIALIZER_OPTION_MODE] == XML_SERIALIZER_MODE_SIMPLEXML) { $string = ''; foreach ($array as $key => $val) { $string .= $this->_serializeValue($val, $tagName, $attributes); $string .= $this->options[XML_SERIALIZER_OPTION_LINEBREAKS]; // do indentation if ($this->options[XML_SERIALIZER_OPTION_INDENT] !== null && $this->_tagDepth > 0) { $string .= str_repeat($this->options[XML_SERIALIZER_OPTION_INDENT], $this->_tagDepth); } } return rtrim($string); } } $scalarAsAttributes = false; if (is_array($this->options[XML_SERIALIZER_OPTION_SCALAR_AS_ATTRIBUTES]) && isset($this->options[XML_SERIALIZER_OPTION_SCALAR_AS_ATTRIBUTES][$tagName])) { $scalarAsAttributes = $this->options[XML_SERIALIZER_OPTION_SCALAR_AS_ATTRIBUTES][$tagName]; } elseif ($this->options[XML_SERIALIZER_OPTION_SCALAR_AS_ATTRIBUTES] === true) { $scalarAsAttributes = true; } if ($scalarAsAttributes === true) { $this->expectError('*'); foreach ($array as $key => $value) { if (is_scalar($value) && XML_Util::isValidName($key) === true) { unset($array[$key]); $attributes[$this->options[XML_SERIALIZER_OPTION_PREPEND_ATTRIBUTES] . $key] = $value; } } $this->popExpect(); } elseif (is_array($scalarAsAttributes)) { $this->expectError('*'); foreach ($scalarAsAttributes as $key) { if (!isset($array[$key])) { continue; } $value = $array[$key]; if (is_scalar($value) && XML_Util::isValidName($key) === true) { unset($array[$key]); $attributes[$this->options[XML_SERIALIZER_OPTION_PREPEND_ATTRIBUTES] . $key] = $value; } } $this->popExpect(); } // check for empty array => create empty tag if (empty($array)) { $tag = array('qname' => $tagName, 'content' => $_content, 'attributes' => $attributes); } else { $this->_tagDepth++; $tmp = $_content . $this->options[XML_SERIALIZER_OPTION_LINEBREAKS]; foreach ($array as $key => $value) { // do indentation if ($this->options[XML_SERIALIZER_OPTION_INDENT] !== null && $this->_tagDepth > 0) { $tmp .= str_repeat($this->options[XML_SERIALIZER_OPTION_INDENT], $this->_tagDepth); } // copy key $origKey = $key; $this->expectError('*'); // key cannot be used as tagname => use default tag $valid = XML_Util::isValidName($key); $this->popExpect(); if (PEAR::isError($valid)) { if ($this->options[XML_SERIALIZER_OPTION_CLASSNAME_AS_TAGNAME] && is_object($value)) { $key = get_class($value); } else { $key = $this->_getDefaultTagname($tagName); } } // once we've established the true $key, is there a tagmap for it? if (isset($this->options[XML_SERIALIZER_OPTION_TAGMAP][$key])) { $key = $this->options[XML_SERIALIZER_OPTION_TAGMAP][$key]; } $atts = array(); if ($this->options[XML_SERIALIZER_OPTION_TYPEHINTS] === true) { $atts[$this->options[XML_SERIALIZER_OPTION_ATTRIBUTE_TYPE]] = gettype($value); if ($key !== $origKey) { $atts[$this->options[XML_SERIALIZER_OPTION_ATTRIBUTE_KEY]] = (string) $origKey; } } $tmp .= $this->_createXMLTag(array('qname' => $key, 'attributes' => $atts, 'content' => $value)); $tmp .= $this->options[XML_SERIALIZER_OPTION_LINEBREAKS]; } $this->_tagDepth--; if ($this->options[XML_SERIALIZER_OPTION_INDENT] !== null && $this->_tagDepth > 0) { $tmp .= str_repeat($this->options[XML_SERIALIZER_OPTION_INDENT], $this->_tagDepth); } if (trim($tmp) === '') { $tmp = null; } $tag = array('qname' => $tagName, 'content' => $tmp, 'attributes' => $attributes); } if ($this->options[XML_SERIALIZER_OPTION_TYPEHINTS] === true) { if (!isset($tag['attributes'][$this->options[XML_SERIALIZER_OPTION_ATTRIBUTE_TYPE]])) { $tag['attributes'][$this->options[XML_SERIALIZER_OPTION_ATTRIBUTE_TYPE]] = 'array'; } } $string = ''; if (!is_null($_comment)) { $string .= XML_Util::createComment($_comment); $string .= $this->options[XML_SERIALIZER_OPTION_LINEBREAKS]; if ($this->options[XML_SERIALIZER_OPTION_INDENT] !== null && $this->_tagDepth > 0) { $string .= str_repeat($this->options[XML_SERIALIZER_OPTION_INDENT], $this->_tagDepth); } } $string .= $this->_createXMLTag($tag, false); return $string; }
function CreateNode($NodeName, $NodeValue) { require_once 'XML/Util.php'; $xml = new XML_Util(); $node = "<" . $NodeName . ">" . $xml->replaceEntities($NodeValue) . "</" . $NodeName . ">"; return $node; }
public static function generateExportData($parameters) { $exportProperties = $aliases = $sid = null; extract($parameters); $listingInfo = SJB_ListingManager::getListingInfoBySID($sid); $listingInfo = $aliases->changePropertiesInfo($listingInfo); $exportData = array(); $i18n = SJB_I18N::getInstance(); foreach ($exportProperties as $propertyId => $value) { if ('ApplicationSettings' == $propertyId) { $exportData[$sid][$propertyId] = isset($listingInfo[$propertyId]['value']) ? $listingInfo[$propertyId]['value'] : null; } else { $fieldInfo = SJB_ListingFieldDBManager::getListingFieldInfoByID($propertyId); if (!empty($fieldInfo['type']) && $fieldInfo['type'] == 'complex' && isset($listingInfo[$propertyId])) { $complexFields = $listingInfo[$propertyId]; if (is_string($listingInfo[$propertyId])) { $complexFields = unserialize($complexFields); } if (is_array($complexFields)) { $fieldsInfo = SJB_ListingComplexFieldManager::getListingFieldsInfoByParentSID($fieldInfo['sid']); foreach ($fieldsInfo as $key => $info) { $fieldsInfo[$info['id']] = $info; unset($fieldsInfo[$key]); } $domDocument = new DOMDocument(); $rootElement = $domDocument->createElement($propertyId . 's'); $domDocument->appendChild($rootElement); $propertyElements = array(); $createPropertyElements = true; foreach ($complexFields as $fieldName => $fieldValue) { $fieldInfo = isset($fieldsInfo[$fieldName]) ? $fieldsInfo[$fieldName] : array(); foreach ($fieldValue as $key => $value) { if (isset($fieldInfo['type']) && $fieldInfo['type'] == 'complexfile' && $value != '') { $fileName = SJB_UploadFileManager::getUploadedSavedFileName($value); $value = $fileName ? 'files/' . $fileName : ''; } elseif (isset($fieldInfo['type']) && $fieldInfo['type'] == 'date' && $value != '') { $value = $i18n->getDate($value); } if ($createPropertyElements) { $propertyElement = $domDocument->createElement($propertyId); $rootElement->appendChild($propertyElement); $propertyElements[$key] = $propertyElement; } $fieldElement = $domDocument->createElement($fieldName); $propertyElements[$key]->appendChild($fieldElement); $valElement = $domDocument->createTextNode(XML_Util::replaceEntities($value)); $fieldElement->appendChild($valElement); } $createPropertyElements = false; } $exportData[$sid][$propertyId] = $domDocument->saveXML(); } else { $exportData[$sid][$propertyId] = null; } } else { $exportData[$sid][$propertyId] = isset($listingInfo[$propertyId]) ? $listingInfo[$propertyId] : null; } } } self::changeTreeProperties($exportProperties, $exportData); self::changeMonetaryProperties($exportProperties, $exportData); self::changeListProperties($exportProperties, $exportData); self::changePicturesProperties($exportProperties, $exportData); self::changeFileProperties($exportProperties, $exportData, 'file'); self::changeFileProperties($exportProperties, $exportData, 'video'); self::changeComplexFileProperties($exportProperties, $exportData, 'complexfile'); self::changeLocationProperties($exportProperties, $exportData); return $exportData[$sid]; }
/** * Serialize the element. * * @access public * @return string string representation of the element and all of its childNodes */ public function serialize() { if (empty($this->_ns) || $this->knownElement === false) { $el = $this->elementName; } else { $el = sprintf('%s:%s', $this->_ns, $this->elementName); } if (!$this->hasChildren()) { if ($this->cdata !== null) { $content = $this->cdata; if ($this->replaceEntities) { $content = XML_Util::replaceEntities($content); } } } else { $content = ''; $rit = new RecursiveIteratorIterator($this, RIT_SELF_FIRST); while ($rit->getSubIterator()->valid()) { $content .= $rit->getSubIterator()->current()->serialize(); $rit->getSubIterator()->next(); } } if ($this->isRoot) { $nsUri = 'http://www.macromedia.com/2003/mxml'; } else { $nsUri = null; } return XML_Util::createTag($el, $this->attributes, $content, $nsUri, false); }
/** * Serialize one metadata element * * @param el object, element object * @param lvl int, level for indentation * @return string, serialized XML */ function serializeEl($el, $lvl = 0) { $ind = str_repeat(" ", $lvl); $elNs = $el->ns; $elName = $el->name; $attrs = XML_Util::attributesToString($el->attrs); $fullName = ($elNs == '' ? '' : "{$elNs}:") . "{$elName}"; $res = "\n{$ind}<{$fullName}{$attrs}>"; $haveCh = count($el->children) > 0; foreach ($el->children as $ch) { $res .= $this->serializeEl($ch, $lvl + 1); } $res .= XML_Util::replaceEntities("{$el->content}"); if ($haveCh) { $res .= "\n{$ind}"; } $res .= "</{$fullName}>"; return $res; }
/** * Generates the XUL for the DataGrid * * @access public * @return string The XUL of the DataGrid */ function toXUL() { $dg =& $this->_dg; // Get the data to be rendered $dg->fetchDataSource(); // Check to see if column headers exist, if not create them // This must follow after any fetch method call $dg->_setDefaultHeaders(); // Define XML $xul = XML_Util::getXMLDeclaration() . "\n"; // Define Stylesheets foreach ($this->css as $css) { $xul .= "<?xml-stylesheet href=\"{$css}\" type=\"text/css\"?>\n"; } // Define Window Element $xul .= "<window title=\"{$this->title}\" " . "xmlns=\"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\">\n"; // Define Listbox Element $xul .= "<listbox rows=\"" . $this->_dg->rowLimit . "\">\n"; // Build Grid Header $xul .= " <listhead>\n"; $prefix = $this->requestPrefix; foreach ($this->_dg->columnSet as $column) { if ($this->_dg->sortArray[0] == $column->orderBy) { if (strtoupper($this->_dg->sortArray[1]) == 'ASC') { // The data is currently sorted by $column, ascending. // That means we want $dirArg set to 'DESC', for the next // click to trigger a reverse order sort, and we need // $dirCur set to 'ascending' so that a neat xul arrow // shows the current "ASC" direction. $dirArg = 'DESC'; $dirCur = 'ascending'; } else { // Next click will do ascending sort, and we show a reverse // arrow because we're currently descending. $dirArg = 'ASC'; $dirCur = 'descending'; } } else { // No current sort on this column. Next click will ascend. We // show no arrow. $dirArg = 'ASC'; $dirCur = 'natural'; } $onClick = "location.href='" . $_SERVER['PHP_SELF'] . '?' . $prefix . 'orderBy=' . $column->orderBy . "&" . $prefix . "direction={$dirArg}';"; $label = XML_Util::replaceEntities($column->columnName); $xul .= ' <listheader label="' . $label . '" ' . "sortDirection=\"{$dirCur}\" onCommand=\"{$onClick}\" />\n"; } $xul .= " </listhead>\n"; // Build Grid Body foreach ($this->_dg->recordSet as $row) { $xul .= " <listitem>\n"; foreach ($this->_dg->columnSet as $column) { // Build Content if ($column->formatter != null) { $content = $column->formatter($row); } elseif ($column->fieldName == null) { if ($column->autoFillValue != null) { $content = $column->autoFillValue; } else { $content = $column->columnName; } } else { $content = $row[$column->fieldName]; } $xul .= ' ' . XML_Util::createTag('listcell', array('label' => $content)) . "\n"; } $xul .= " </listitem>\n"; } $xul .= "</listbox>\n"; $xul .= "</window>\n"; return $xul; }