/** * Converts a data array into an XML * @access public * @static * @param array $data * @param array $file */ public static function data2XML($data, $file){ $group=array(); if(isset($data['_Token'])){ unset($data['_Token']); } if(isset($data['Control'])){ unset($data['Control']); } $encodedData = self::arrayEncodeXML($data); $xmlData = array('root' => $encodedData); $xmlObject = Xml::fromArray($xmlData, array('format' => 'tags')); $xmlString = $xmlObject->asXML(); file_put_contents ($file , $xmlString); }
/** * Serialize view vars. * * @param array $serialize The viewVars that need to be serialized. * @return string The serialized data */ protected function _serialize($serialize) { $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response'; if (is_array($serialize)) { $data = array($rootNode => array()); foreach ($serialize as $alias => $key) { if (is_numeric($alias)) { $alias = $key; } $data[$rootNode][$alias] = $this->viewVars[$key]; } } else { $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; if (is_array($data) && Set::numeric(array_keys($data))) { $data = array($rootNode => array($serialize => $data)); } } $options = array(); if (Configure::read('debug')) { $options['pretty'] = true; } return Xml::fromArray($data, $options)->asXML(); }
/** * testNamespace * * @return void */ public function testNamespace() { $xmlResponse = Xml::build('<root xmlns:ns="http://cakephp.org"><ns:tag id="1"><child>good</child><otherchild>bad</otherchild></ns:tag><tag>Tag without ns</tag></root>'); $expected = array('root' => array('ns:tag' => array('@id' => '1', 'child' => 'good', 'otherchild' => 'bad'), 'tag' => 'Tag without ns')); $this->assertEquals(Xml::toArray($xmlResponse), $expected); $xmlResponse = Xml::build('<root xmlns:ns="http://cakephp.org"><ns:tag id="1" /><tag><id>1</id></tag></root>'); $expected = array('root' => array('ns:tag' => array('@id' => '1'), 'tag' => array('id' => '1'))); $this->assertEquals(Xml::toArray($xmlResponse), $expected); $xmlResponse = Xml::build('<root xmlns:ns="http://cakephp.org"><ns:attr>1</ns:attr></root>'); $expected = array('root' => array('ns:attr' => '1')); $this->assertEquals(Xml::toArray($xmlResponse), $expected); $xmlResponse = Xml::build('<root><ns:attr xmlns:ns="http://cakephp.org">1</ns:attr></root>'); $this->assertEquals(Xml::toArray($xmlResponse), $expected); $xml = array('root' => array('ns:attr' => array('xmlns:ns' => 'http://cakephp.org', '@' => 1))); $expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root><ns:attr xmlns:ns="http://cakephp.org">1</ns:attr></root>'; $xmlResponse = Xml::fromArray($xml); $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); $xml = array('root' => array('tag' => array('xmlns:pref' => 'http://cakephp.org', 'pref:item' => array('item 1', 'item 2')))); $expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root><tag xmlns:pref="http://cakephp.org"><pref:item>item 1</pref:item><pref:item>item 2</pref:item></tag></root>'; $xmlResponse = Xml::fromArray($xml); $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); $xml = array('root' => array('tag' => array('xmlns:' => 'http://cakephp.org'))); $expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root><tag xmlns="http://cakephp.org"/></root>'; $xmlResponse = Xml::fromArray($xml); $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); $xml = array('root' => array('xmlns:' => 'http://cakephp.org')); $expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root xmlns="http://cakephp.org"/>'; $xmlResponse = Xml::fromArray($xml); $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); $xml = array('root' => array('xmlns:ns' => 'http://cakephp.org')); $expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root xmlns:ns="http://cakephp.org"/>'; $xmlResponse = Xml::fromArray($xml); $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); }
/** * Uploads the attribute to another Server * TODO move this to a component * * @return bool true if success, error message if failed */ public function restfullAttributeToServer($attribute, $server, $urlPath, $HttpSocket = null) { // do not keep attributes that are private if (0 == $attribute['distribution']) { // never upload private events return "Attribute is private and non exportable"; } $url = $server['Server']['url']; $authkey = $server['Server']['authkey']; if (null == $HttpSocket) { App::uses('SyncTool', 'Tools'); $syncTool = new SyncTool(); $HttpSocket = $syncTool->setupHttpSocket($server); } $request = array('header' => array('Authorization' => $authkey, 'Accept' => 'application/xml', 'Content-Type' => 'application/xml')); $uri = isset($urlPath) ? $urlPath : $url . '/attributes'; // LATER try to do this using a separate EventsController and renderAs() function $xmlArray = array(); // cleanup the array from things we do not want to expose //unset($event['Event']['org']); // remove value1 and value2 from the output unset($attribute['value1']); unset($attribute['value2']); // also add the encoded attachment if ($this->typeIsAttachment($attribute['type'])) { $encodedFile = $this->base64EncodeAttachment($attribute); $attribute['data'] = $encodedFile; } // display the XML to the user $xmlArray['Attribute'] = $attribute; $xmlObject = Xml::fromArray($xmlArray, array('format' => 'tags')); $attributesXml = $xmlObject->asXML(); // do a REST POST request with the server $data = $attributesXml; // LATER validate HTTPS SSL certificate $this->Dns = ClassRegistry::init('Dns'); if ($this->Dns->testipaddress(parse_url($uri, PHP_URL_HOST))) { // TODO NETWORK for now do not know how to catch the following.. // TODO NETWORK No route to host $response = $HttpSocket->post($uri, $data, $request); switch ($response->code) { case '200': // 200 (OK) + entity-action-result if ($response->isOk()) { return isset($urlPath) ? $response->body() : true; } else { try { // parse the XML response and keep the reason why it failed $xmlArray = Xml::toArray(Xml::build($response->body)); } catch (XmlException $e) { return true; } if (strpos($xmlArray['response']['name'], "Attribute already exists")) { // strpos, so i can piggyback some value if needed. return true; } else { return $xmlArray['response']['name']; } } break; case '302': // Found // Found case '404': // Not Found return isset($urlPath) ? $response->body() : $response->headers['Location']; break; } } }
/** * Serialize view vars * * @param array $serialize The viewVars that need to be serialized * @return string The serialized data */ protected function _serialize($serialize) { $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response'; if (is_array($serialize)) { $data = array($rootNode => array()); foreach ($serialize as $key) { $data[$rootNode][$key] = $this->viewVars[$key]; } } else { $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; if (is_array($data) && Set::numeric(array_keys($data))) { $data = array($rootNode => array($serialize => $data)); } } return Xml::fromArray($data)->asXML(); }
/** * Generate a XML for request * * @param string $method Name of method * @param array $params List of methods * @return string XML of request */ public function generateXML($method, $params = array()) { $query = array('methodCall' => array('methodName' => $method, 'params' => array())); if (!empty($params)) { $query['methodCall']['params']['param'] = array(); foreach ($params as $param) { $query['methodCall']['params']['param'][] = $this->_normalizeParam($param); } } $Xml = Xml::fromArray($query, array('format' => 'tags')); return $Xml->asXml(); }
/** * Render a XML view. * * Uses the special '_serialize' parameter to convert a set of * view variables into a XML response. Makes generating simple * XML responses very easy. You can omit the '_serialize' parameter, * and use a normal view + layout as well. * * @param string $view The view being rendered. * @param string $layout The layout being rendered. * @return string The rendered view. */ public function render($view = null, $layout = null) { if (isset($this->viewVars['_serialize'])) { $serialize = $this->viewVars['_serialize']; if (is_array($serialize)) { $data = array('response' => array()); foreach ($serialize as $key) { $data['response'][$key] = $this->viewVars[$key]; } } else { $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; if (is_array($data) && Set::numeric(array_keys($data))) { $data = array('response' => array($serialize => $data)); } } $content = Xml::fromArray($data)->asXML(); return $content; } if ($view !== false && ($viewFileName = $this->_getViewFileName($view))) { if (!$this->_helpersLoaded) { $this->loadHelpers(); } $content = $this->_render($viewFileName); $this->Blocks->set('content', (string) $content); return $content; } }
/** * Uploads the event and the associated Attributes to another Server * TODO move this to a component * * @return bool true if success, false or error message if failed */ public function restfullEventToServer($event, $server, $urlPath, &$newLocation, &$newTextBody, $HttpSocket = null) { if ($event['Event']['distribution'] < 2) { // never upload private events return 403; //"Event is private and non exportable"; } $url = $server['Server']['url']; $authkey = $server['Server']['authkey']; if (null == $HttpSocket) { App::uses('HttpSocket', 'Network/Http'); $HttpSocket = new HttpSocket(); } $request = array('header' => array('Authorization' => $authkey, 'Accept' => 'application/xml', 'Content-Type' => 'application/xml')); $uri = isset($urlPath) ? $urlPath : $url . '/events'; // LATER try to do this using a separate EventsController and renderAs() function $xmlArray = array(); // rearrange things to be compatible with the Xml::fromArray() $event['Event']['Attribute'] = $event['Attribute']; unset($event['Attribute']); // cleanup the array from things we do not want to expose //unset($event['Event']['org']); // remove value1 and value2 from the output foreach ($event['Event']['Attribute'] as $key => &$attribute) { // do not keep attributes that are private, nor cluster if ($attribute['distribution'] < 2) { unset($event['Event']['Attribute'][$key]); continue; // stop processing this } // Distribution, correct Connected Community to Community in Attribute if ($attribute['distribution'] == 2) { $attribute['distribution'] = 1; } // remove value1 and value2 from the output unset($attribute['value1']); unset($attribute['value2']); // also add the encoded attachment if ($this->Attribute->typeIsAttachment($attribute['type'])) { $encodedFile = $this->Attribute->base64EncodeAttachment($attribute); $attribute['data'] = $encodedFile; } // Passing the attribute ID together with the attribute could cause the deletion of attributes after a publish/push // Basically, if the attribute count differed between two instances, and the instance with the lower attribute // count pushed, the old attributes with the same ID got overwritten. Unsetting the ID before pushing it // solves the issue and a new attribute is always created. unset($attribute['id']); } // Distribution, correct All to Community in Event if ($event['Event']['distribution'] == 2) { $event['Event']['distribution'] = 1; } // display the XML to the user $xmlArray['Event'][] = $event['Event']; $xmlObject = Xml::fromArray($xmlArray, array('format' => 'tags')); $eventsXml = $xmlObject->asXML(); // do a REST POST request with the server $data = $eventsXml; // LATER validate HTTPS SSL certificate $this->Dns = ClassRegistry::init('Dns'); if ($this->Dns->testipaddress(parse_url($uri, PHP_URL_HOST))) { // TODO NETWORK for now do not know how to catch the following.. // TODO NETWORK No route to host $response = $HttpSocket->post($uri, $data, $request); switch ($response->code) { case '200': // 200 (OK) + entity-action-result if ($response->isOk()) { $newTextBody = $response->body(); $newLocation = null; return true; //return isset($urlPath) ? $response->body() : true; } else { try { // parse the XML response and keep the reason why it failed $xmlArray = Xml::toArray(Xml::build($response->body)); } catch (XmlException $e) { return true; // TODO should be false } if (strpos($xmlArray['response']['name'], "Event already exists")) { // strpos, so i can piggyback some value if needed. return true; } else { return $xmlArray['response']['name']; } } break; case '302': // Found $newLocation = $response->headers['Location']; $newTextBody = $response->body(); return true; //return isset($urlPath) ? $response->body() : $response->headers['Location']; break; case '404': // Not Found $newLocation = $response->headers['Location']; $newTextBody = $response->body(); return 404; break; case '405': return 405; break; case '403': // Not authorised return 403; break; } } }
/** * Serialize view vars. * * @param string|array $serialize The viewVars that need to be serialized. * @return string The serialized data * @throws RuntimeException When the prefix is not specified */ protected function _serialize($serialize) { $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel'; if (is_array($serialize)) { $data = array($rootNode => array()); foreach ($serialize as $alias => $key) { if (is_numeric($alias)) { $alias = $key; } $data[$rootNode][$alias] = $this->viewVars[$key]; } } else { $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; if (is_array($data) && Hash::numeric(array_keys($data))) { $data = array($rootNode => array($serialize => $data)); } } $defaults = array('document' => array(), 'channel' => array(), 'items' => array()); $data += $defaults; if (!empty($data['document']['namespace'])) { foreach ($data['document']['namespace'] as $prefix => $url) { $this->setNamespace($prefix, $url); } } $channel = $this->channel($data['channel']); if (!empty($channel['image']) && empty($channel['image']['title'])) { $channel['image']['title'] = $channel['title']; } foreach ($data['items'] as $item) { $channel['item'][] = $this->_prepareOutput($item); } $array = array('rss' => array('@version' => $this->version, 'channel' => $channel)); $namespaces = array(); foreach ($this->_usedNamespaces as $usedNamespacePrefix) { if (!isset($this->_namespaces[$usedNamespacePrefix])) { throw new RuntimeException(__('The prefix %s is not specified.', $usedNamespacePrefix)); } $namespaces['xmlns:' . $usedNamespacePrefix] = $this->_namespaces[$usedNamespacePrefix]; } $array['rss'] += $namespaces; $options = array(); if (Configure::read('debug')) { $options['pretty'] = true; } $output = Xml::fromArray($array, $options)->asXML(); $output = $this->_replaceCdata($output); return $output; }
/** * @param array $payload * @param bool $response If true, the $responseFormat will be used, otherwise the $requestFormat * @param bool $assocArray If true, decoded JSON is returned in an array * * @return array|string */ protected function _translatePayload($payload = array(), $response = true, $assocArray = true) { $_format = $response ? $this->_responseFormat : $this->_requestFormat; $_payload = $payload; switch ($_format) { case DataFormatTypes::JSON: if (true === $response) { if (is_string($_payload) && !empty($_payload)) { $_payload = json_decode($payload, $assocArray); } } else { if (!is_string($_payload)) { $_payload = json_encode($_payload); } } if (false === $_payload) { // Revert because it failed to go to JSON $_payload = $payload; } break; case DataFormatTypes::XML: if (is_object($payload)) { $_payload = Xml::fromObject($payload); } else { if (is_array($payload)) { $_payload = Xml::fromArray($payload); } } break; } return $_payload; }
public static function xmlElem($name, $attributes = array(), $content = null) { $attributes['@'] = $content; $data = array($name => $attributes); $retval = Xml::fromArray($data, array('format' => 'attribute', 'encoding' => null))->asXML(); $retval = str_replace(array("<?xml version=\"1.0\"?>", "\n"), "", $retval); return html_entity_decode($retval); }
public function montarXml($tipo = null) { $elemento_base = $tipo; $xml[$elemento_base] = array('@versao' => '1.2.0', '@id' => $this->xml_id, '@xmlns' => 'http://ecommerce.cbmp.com.br'); if ($tipo == "requisicao-cancelamento" or $tipo == "requisicao-consulta" or $tipo == "requisicao-captura") { $xml[$elemento_base]['tid'] = $this->tid; } $xml[$elemento_base]['dados-ec']['numero'] = $this->loja_id; $xml[$elemento_base]['dados-ec']['chave'] = $this->loja_chave; if ($tipo == "requisicao-transacao") { if (!$this->buy_page_cielo) { $xml[$elemento_base]['dados-portador']['numero'] = $this->cc_numero; $xml[$elemento_base]['dados-portador']['validade'] = $this->cc_validade; $xml[$elemento_base]['dados-portador']['indicador'] = '1'; $xml[$elemento_base]['dados-portador']['codigo-seguranca'] = $this->cc_codigo_seguranca; } $xml[$elemento_base]['dados-pedido']['numero'] = $this->pedido_id; $xml[$elemento_base]['dados-pedido']['valor'] = $this->pedido_valor; $xml[$elemento_base]['dados-pedido']['moeda'] = '986'; $xml[$elemento_base]['dados-pedido']['data-hora'] = $this->pedido_data_hora; $xml[$elemento_base]['dados-pedido']['idioma'] = 'PT'; $xml[$elemento_base]['forma-pagamento']['bandeira'] = $this->cc_bandeira; $xml[$elemento_base]['forma-pagamento']['produto'] = $this->cc_produto; $xml[$elemento_base]['forma-pagamento']['parcelas'] = $this->pagamento_qtd_parcelas; $xml[$elemento_base]['url-retorno'] = $this->url_retorno; $xml[$elemento_base]['autorizar'] = $this->autorizar; $xml[$elemento_base]['capturar'] = $this->capturar ? 'true' : 'false'; } if (!is_null($this->valor_capturar) and $tipo == "requisicao-captura") { $xml[$elemento_base]['valor'] = $this->valor_capturar; } $xml = Xml::fromArray($xml, array('encoding' => 'ISO-8859-1', 'format' => 'tags')); return $xml->asXML(); }
/** * updateGroup * * @return mixed */ public function createGroup($title) { $g = array(); $g['atom:entry'] = array(); $g['atom:entry']['xmlns:atom'] = 'http://www.w3.org/2005/Atom'; $g['atom:entry']['xmlns:gd'] = 'http://schemas.google.com/g/2005'; $g['atom:entry']['atom:title'] = array('@' => $title, '@type' => 'text'); $groupXml = Xml::fromArray($g, array('format' => 'tags')); $response = $this->Client->fetch(sprintf('https://www.google.com/m8/feeds/groups/%1$s/full/', $this->user), substr($groupXml->saveXML(), 39), 'POST', array('Content-Type' => 'application/atom+xml', 'GData-Version' => '3.0')); if ($response['code'] == 201) { $xmlGroup = Xml::build($response['result']); $groupArray = Xml::toArray($xmlGroup); return new LiLCrmGoogleGroup($groupArray['entry']); } else { return false; } }
private function __toXml() { $xmlObject = Xml::fromArray($this->__errorArray()); $xmlString = $xmlObject->asXML(); header('Content-type: application/xml'); echo $xmlString; die; }