/** * Procesar */ public function process() { foreach (glob($this->_dir_temp . "/*.kml") as $filename) { //convertir KML a array $data = Zend_Json::decode(Zend_Json::fromXml(file_get_contents($filename), false)); $this->_findPlacemarks($data); $this->_findStyles($data); $this->_findStylesMap($data); } if (count($this->_placemarks) > 0) { foreach ($this->_placemarks as $key => $placemark) { if (isset($placemark[0])) { foreach ($placemark as $elemento) { $this->_procesaPunto($elemento); $this->_procesaPoligono($elemento); $this->_procesaMultiPoligono($elemento); $this->_procesaLinea($elemento); $this->_procesaMultiLinea($elemento); } } else { $this->_procesaPunto($placemark); $this->_procesaPoligono($placemark); $this->_procesaMultiPoligono($placemark); $this->_procesaLinea($placemark); $this->_procesaMultiLinea($placemark); } } } //se agregan los elementos al cache que contiene el archivo $cache = Cache::iniciar(); $data = $cache->load($this->_hash); $data["elementos"] = $this->_elementos; $cache->save($data, $this->_hash); return $this->_elementos; }
/** * Carga el KML desde sidco * @return type */ protected function _loadKml() { $zfClient = new Zend_Http_Client($this->_kml_path); $zfClient->setConfig(array('timeout' => 45)); $zfClient->setMethod(Zend_Http_Client::GET); $kml = json_decode(Zend_Json::fromXml($zfClient->request()->getBody())); return $kml; }
/** * Deserialize XML to PHP value * * @param string $json * @param array $opts * @return mixed */ public function unserialize($xml, array $opts = array()) { try { $json = Zend_Json::fromXml($xml); return (array) Zend_Json::decode($json, Zend_Json::TYPE_OBJECT); } catch (Exception $e) { require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); } }
public function direct($xmlDoc) { $request = $this->getRequest(); $response = new Zend_Controller_Response_Http(); $responseFormat = $request->getParam("responseformat", "xml"); $xmlDoc->encoding = "utf-8"; $xml = $xmlDoc->saveXML(); if ($responseFormat == 'json') { echo Zend_Json::fromXml($xml, false); } else { echo $xml; } }
protected function _render($xml) { if ('json' == $this->_format) { header("Content-type: text/javascript;"); echo Zend_Json::fromXml($xml, true); } else { header("Content-type: text/xml;"); echo $xml; } exit; }
/** * Retourne un tableau contenant l'opportunité depuis le code dans pi_flexform */ private function getPack() { $dataXML = Zend_Json::fromXml($this->cObj->data['pi_flexform']); $dataFlexform = Zend_Json::decode($dataXML, Zend_Json::TYPE_ARRAY); $packCode = $dataFlexform["T3FlexForms"]["data"]["sheet"]["language"]["field"]["value"]; $subUrl = "opportunity/code/" . $packCode; $data = $this->getDataJson($subUrl); $data["Code"] = $packCode; return $data; }
public function testJsonAndXmlOutputEquivalentData() { $this->dispatch('/ot/api/json/?method=describe'); $this->assertResponseCode(200); $this->assertNotRedirect(); $this->assertModule('ot'); $this->assertController('api'); $this->assertAction('json'); $jsonResponseObject = $this->response->outputBody(); $this->_response = null; // clear the response, so the xml that we grab next doesn't have json before it. $this->dispatch('/ot/api/xml/?method=describe'); $this->assertResponseCode(200); $this->assertNotRedirect(); $this->assertModule('ot'); $this->assertController('api'); $this->assertAction('xml'); // this might make this test useless....: $xmlResponseObject = Zend_Json::fromXml($this->response->outputBody()); $this->assertEquals($jsonResponseObject, $xmlResponseObject); }
/** * Encode Json From xml * * @param String $xml * @return String */ public static function EncodeXml($xml) { return Zend_Json::fromXml($xml); }
/** * xml2json Test 6 * It tests the conversion of demo application xml into Json format. * * XML characteristic to be tested: XML containing a large CDATA. * */ public function testUsingXML6() { // Set the XML contents that will be tested here. $xmlStringContents = <<<EOT <?xml version="1.0"?> <demo> <application> <name>Killer Demo</name> </application> <author> <name>John Doe</name> </author> <platform> <name>LAMP</name> </platform> <framework> <name>Zend</name> </framework> <language> <name>PHP</name> </language> <listing> <code> <![CDATA[ /* It may not be a syntactically valid PHP code. It is used here just to illustrate the CDATA feature of Zend_Xml2Json */ <?php include 'example.php'; new SimpleXMLElement(); echo(getMovies()->movie[0]->characters->addChild('character')); getMovies()->movie[0]->characters->character->addChild('name', "Mr. Parser"); getMovies()->movie[0]->characters->character->addChild('actor', "John Doe"); // Add it as a child element. getMovies()->movie[0]->addChild('rating', 'PG'); getMovies()->movie[0]->rating->addAttribute("type", 'mpaa'); echo getMovies()->asXML(); ?> ]]> </code> </listing> </demo> EOT; // There are not going to be any XML attributes in this test XML. // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = true; $jsonContents = ""; $ex = null; // Convert XNL to JSON now. // fromXml function simply takes a String containing XML contents as input. try { $jsonContents = Zend_Json::fromXml($xmlStringContents, $ignoreXmlAttributes); } catch (Exception $ex) { } $this->assertSame($ex, null, "Zend_JSON::fromXml returned an exception."); // Convert the JSON string into a PHP array. $phpArray = Zend_Json::decode($jsonContents); // Test if it is not a NULL object. $this->assertNotNull($phpArray, "JSON result for XML input 6 is NULL"); // Test for one of the expected fields in the JSON result. $this->assertContains("Zend", $phpArray['demo']['framework']['name'], "The framework name field converted from XML input 6 is not correct"); // Test for one of the expected CDATA fields in the JSON result. $this->assertContains('echo getMovies()->asXML();', $phpArray['demo']['listing']['code'], "The CDATA code converted from XML input 6 is not correct"); }
/** * Handles all GET requests to a web service * * @param string $method Requested API method * @param array $params Array of GET parameters * @return mixed decoded response from web service * @throws Bgy_Service_Geonames_Exception */ public function makeRequest($method, $params = array()) { $this->_rest->setUri(self::API_URI); $path = $method; $type = self::$_supportedMethods[$path]['output']; // Construct the path accordingly to the output type switch ($type) { case 'json': $path = $path . 'JSON'; break; case 'xml': $params += array('type' => 'xml'); break; default: /** * @see Bgy_Service_Geonames_Exception */ require_once 'Bgy/Service/Geonames/Exception.php'; throw new Bgy_Service_Geonames_Exception('Unknown request type'); } if (null !== $this->getUsername()) { $params['username'] = $this->getUsername(); } if (null !== $this->getToken()) { $params['token'] = $this->getToken(); } $response = $this->_rest->restGet($path, $params); if (!$response->isSuccessful()) { /** * @see Bgy_Service_Geonames_Exception */ require_once 'Bgy/Service/Geonames/Exception.php'; throw new Bgy_Service_Geonames_Exception("Http client reported an error: '{$response->getMessage()}'"); } $responseBody = $response->getBody(); switch ($type) { case 'xml': $dom = new DOMDocument(); if (!@$dom->loadXML($responseBody)) { /** * @see Bgy_Service_Geonames_Exception */ require_once 'Bgy/Service/Geonames/Exception.php'; throw new Bgy_Service_Geonames_Exception('Malformed XML'); } $jsonResult = Zend_Json::fromXml($dom->saveXML()); break; case 'json': $jsonResult = $responseBody; break; } $arrayFromJson = Zend_Json::decode($jsonResult); if (isset(self::$_supportedMethods[$method]['root']) && null !== ($root = self::$_supportedMethods[$method]['root']) && isset($arrayFromJson[$root])) { $arrayFromJson = $arrayFromJson[$root]; } return $arrayFromJson; }
/** * @group ZF-3257 */ public function testUsingXML8() { // Set the XML contents that will be tested here. $xmlStringContents = <<<EOT <?xml version="1.0"?> <a><b id="foo" />bar</a> EOT; // There are not going to be any XML attributes in this test XML. // Hence, set the flag to ignore XML attributes. $ignoreXmlAttributes = false; $jsonContents = ""; $ex = null; // Convert XML to JSON now. // fromXml function simply takes a String containing XML contents as input. try { $jsonContents = Zend_Json::fromXml($xmlStringContents, $ignoreXmlAttributes); } catch (Exception $ex) { } $this->assertSame($ex, null, "Zend_JSON::fromXml returned an exception."); // Convert the JSON string into a PHP array. $phpArray = Zend_Json::decode($jsonContents); // Test if it is not a NULL object. $this->assertNotNull($phpArray, "JSON result for XML input 1 is NULL"); $this->assertSame("bar", $phpArray['a']['@text'], "The text element of a is not correct"); $this->assertSame("foo", $phpArray['a']['b']['@attributes']['id'], "The id attribute of b is not correct"); }
/** * Transfoms the response body (xml or json) into an array we can more easily * work with. * * @param Zend_Http_Response $response * @return array * @todo $this->_errors is populated with errors from Chargify. Should this * also populate a separate errors array when we get HTTP 404s or 201s? */ public function getResponseArray(Zend_Http_Response $response) { $return = array(); $format = $this->getService()->getFormat(); $body = $response->getBody(); $body = trim($body); /** * return early on bad status codes */ $code = $response->getStatus(); $errorCodes = array(404, 401, 500); if (in_array($code, $errorCodes)) { $this->_errors['Crucial_Service_Chargify']['Bad status code'] = $code; return $return; } /** * Return early if we have an empty body, which we can't turn into an array * anyway. This happens in cases where the API returns a 404, and possibly * other status codes. */ if (empty($body)) { return $return; } if ('json' == $format) { $return = Zend_Json::decode($body); } if ('xml' == $format) { $json = Zend_Json::fromXml($body); $return = Zend_Json::decode($json); } // set errors, if any if (!empty($return['errors'])) { $this->_errors = $return['errors']; } return $return; }
<?php ob_start(); echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n"; ?> <Response> <Meta> <ExecutionTime><?php echo LsApi::getResponseTime(); ?> </ExecutionTime> </Meta> <Data> <?php echo $sf_content; ?> </Data> </Response> <?php $xml = ob_get_contents(); ob_end_clean(); echo Zend_Json::fromXml($xml);
/** * This is method fault * * @param mixed $exception * This is a description * @param mixed $format * This is a description * @param mixed $httpCode * This is a description * @return mixed This is the return value description */ public function fault($exception = null, $format = 'json', $httpCode = null) { $error = false; if ($exception instanceof OAuthException) { $error = ['code' => $exception->getCode(), 'message' => $exception->getMessage()]; } else { if ($exception instanceof \Exception) { $error = ['code' => $exception->getCode(), 'message' => $exception->getMessage()]; } else { $error = ['code' => BAD_URL, 'message' => static::getError(BAD_URL)]; } } switch ($format) { case 'xml': $errorXml = Response::error($error['code'], $error['message']); return $errorXml; case 'plain-text': return Response::plain($error); case 'json': $errorXml = Response::error($error['code'], $error['message'], false); return Zend_Json::fromXml($errorXml); } }
public function membersAction() { $page = $this->_getParam('page'); if (!$this->_cache->test('members')) { $query = 'getMps'; $output = '&output=xml'; $key = '&key=' . self::TWFYAPIKEY; $twfy = self::TWFYURL . $query . $output . $key; $data = Zend_Json::fromXml($this->get($twfy), true); $data = json_decode($data); $this->_cache->save($data); } else { $data = $this->_cache->load('members'); } $data2 = array(); foreach ($data->twfy->match as $a) { if (in_array($a->constituency, $this->_remove)) { unset($a->name); unset($a->person_id); unset($a->party); unset($a->constituency); } if (isset($a->name)) { $data2[] = array('name' => $a->name, 'person_id' => $a->person_id, 'constituency' => $a->constituency, 'party' => $a->party); } } $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($data2)); if (isset($page) && $page != "") { $paginator->setCurrentPageNumber((int) $page); } $paginator->setItemCountPerPage(40)->setPageRange(10); if (in_array($this->_helper->contextSwitch()->getCurrentContext(), array('xml', 'json'))) { $data = array('pageNumber' => $paginator->getCurrentPageNumber(), 'total' => number_format($paginator->getTotalItemCount(), 0), 'itemsReturned' => $paginator->getCurrentItemCount(), 'totalPages' => number_format($paginator->getTotalItemCount() / $paginator->getItemCountPerPage(), 0)); $this->view->data = $data; $members = array(); foreach ($paginator as $k => $v) { $members[] = array(); $members[$k] = $v; } $this->view->members = $members; } else { $this->view->data = $paginator; } }
/** * Searchs for backtweets according to the feed search filter and * returns the response * * @param array $searchFilter * @param boolean $convertResponseIntoArray * @return mixed */ public function search(array $searchFilter, $convertResponseIntoArray = false) { $response = $this->_apiRequest($searchFilter); if ($convertResponseIntoArray) { if ('json' === $this->_responseFormat) { $response = Zend_Json::decode($response); } elseif ('xml' === $this->_responseFormat) { $response = Zend_Json::decode(Zend_Json::fromXml($response)); } } return $response; }
/** * PHP only parses the body into $_POST if its a POST request * this parses the reqest body in accordance with RFC2616 spec regardless of the HTTP method */ private function handleRequestBody(Zend_Controller_Request_Abstract $request) { $header = strtolower($request->getHeader('Content-Type')); // cleanup the charset part $header = current(explode(';', $header)); // detect request body content type foreach ($this->requestTypes as $contentType) { if ($header == $contentType) { break; } } // extract the raw body $rawBody = $request->getRawBody(); // treat these two separately because of the way PHP treats POST if (in_array($contentType, array('multipart/form-data', 'application/x-www-form-urlencoded'))) { // PHP takes care of everything for us in this case lets just modify the $_FILES array if ($request->isPost() && $contentType == 'multipart/form-data') { // if there are files, lets modify the array to match what we've done below foreach ($_FILES as &$file) { $data = file_get_contents($file['tmp_name']); $file['content'] = base64_encode($data); } // reset the array pointer unset($file); } else { switch ($contentType) { case 'application/x-www-form-urlencoded': parse_str($rawBody, $_POST); break; // this is wher the magic happens // creates the $_FILES array for none POST requests // this is wher the magic happens // creates the $_FILES array for none POST requests case 'multipart/form-data': // extract the boundary parse_str(end(explode(';', $request->getHeader('Content-Type')))); if (isset($boundary)) { // get rid of the boundary at the edges if (preg_match(sprintf('/--%s(.+)--%s--/s', $boundary, $boundary), $rawBody, $regs)) { // split into chuncks $chunks = explode('--' . $boundary, trim($regs[1])); foreach ($chunks as $chunk) { // parse each chunk if (preg_match('/Content-Disposition: form-data; name="(?P<name>.+?)"(?:; filename="(?P<filename>.+?)")?(?P<headers>(?:\\r|\\n)+?.+?(?:\\r|\\n)+?)?(?P<data>.+)/si', $chunk, $regs)) { // dedect a file upload if (!empty($regs['filename'])) { // put aside for further analysis $data = $regs['data']; $headers = $this->parseHeaders($regs['headers']); // set our params variable $_FILES[$regs['name']] = array('name' => $regs['filename'], 'type' => $headers['Content-Type'], 'size' => mb_strlen($data), 'content' => base64_encode($data)); // otherwise its a regular key=value combination } else { $_POST[$regs['name']] = trim($regs['data']); } } } } } break; } } $request->setParams($_POST + $_FILES); } elseif (!empty($rawBody)) { // seems like we are dealing with an encoded request try { switch ($contentType) { case 'text/javascript': case 'application/json': case 'application/javascript': $_POST = (array) Zend_Json::decode($rawBody, Zend_Json::TYPE_OBJECT); break; case 'text/xml': case 'application/xml': $json = @Zend_Json::fromXml($rawBody); $_POST = (array) Zend_Json::decode($json, Zend_Json::TYPE_OBJECT)->request; break; case 'text/php': case 'application/x-httpd-php': case 'application/x-httpd-php-source': $_POST = (array) unserialize($rawBody); break; default: $_POST = (array) $rawBody; break; } $request->setParams($_POST); } catch (Exception $e) { $request->dispatchError(REST_Response::BAD_REQUEST, 'Invalid Payload Format'); return; } } }
/** * @group ZF-11385 * @dataProvider providerNestingDepthIsHandledProperly */ public function testNestingDepthIsHandledProperlyWhenNestingDepthDoesNotExceedMaximum($xmlStringContents) { try { Zend_Json::$maxRecursionDepthAllowed = 25; $jsonString = Zend_Json::fromXml($xmlStringContents, true); $jsonArray = Zend_Json::decode($jsonString); $this->assertNotNull($jsonArray, "JSON decode result is NULL"); $this->assertSame('A', $jsonArray['response']['message_type']['defaults']['close_rules']['after_responses']); } catch (Zend_Json_Exception $ex) { $this->fail('Zend_Json::fromXml does not implement recursion check properly'); } }
$ignoreXmlAttributes = true; // Read the filename from the command line. if ($argc <= 1) { print "Please provide the XML filename as a command-line argument:\n"; print "\tphp -f Zend_xml2json_test.php test1.xml\n"; print "You can also provide an optional second argument as 1 or 0. Default is 1.\n"; print "1 means ignore XML atrributes in xml2json conversion. 0 means don't ignore XML attributes.\n"; print "\tphp -f Zend_xml2json_test.php test1.xml 1\n"; return; } else { // Get the XML filename from the command line argument. $testXmlFile = $argv[1]; // Get the optional argument to ingore or not ignore the XML attributes. if ($argc == 3 && $argv[2] == "0") { $ignoreXmlAttributes = false; } // End of if (($argc == 3) && ($argv[2] == "0")) } // End of if ($argc <= 1) //Read the XML contents from the input file. file_exists($testXmlFile) or die('Could not find file ' . $testXmlFile); $xmlStringContents = file_get_contents($testXmlFile); $jsonContents = ""; // Convert it to JSON now. // fromXml function simply takes a String containing XML contents as input. $jsonContents = Zend_Json::fromXml($xmlStringContents, $ignoreXmlAttributes); echo "JSON formatted output generated by Zend_Json::fromXml\n\n"; echo $jsonContents; ?>
/** define an executable */ public function defineAction() { $itemId = $this->getParam('itemId'); if (!isset($itemId) || !is_numeric($itemId)) { throw new Zend_Exception('itemId should be a number'); } $isAjax = $this->getRequest()->isXmlHttpRequest(); $this->view->isAjax = $isAjax; if ($isAjax) { $this->disableLayout(); } $itemDao = $this->Item->load($itemId); if ($itemDao === false) { throw new Zend_Exception("This item doesn't exist."); } if (!$this->Item->policyCheck($itemDao, $this->userSession->Dao, MIDAS_POLICY_WRITE)) { throw new Zend_Exception('Problem policies.'); } $this->view->header = $this->t('Manage Configuration: ' . $itemDao->getName()); $metaFile = $this->ModuleComponent->Executable->getMetaIoFile($itemDao); if (isset($_GET['init'])) { $this->showNotificationMessage('Please set the option of the executable first.'); } $jsonContents = JsonComponent::encode(array()); if ($metaFile !== false) { $jsonContents = Zend_Json::fromXml(file_get_contents($metaFile->getFullPath()), true); } $this->view->itemDao = $itemDao; $this->view->jsonMetadata = $jsonContents; $this->view->json['item'] = $itemDao->toArray(); if ($this->_request->isPost()) { $this->disableLayout(); $this->disableView(); $results = $_POST['results']; $xmlContent = $this->ModuleComponent->Executable->createDefinitionFile($results); /** @var RandomComponent $randomComponent */ $randomComponent = MidasLoader::loadComponent('Random'); $pathFile = $this->getTempDirectory() . '/' . $randomComponent->generateString(32); file_put_contents($pathFile, $xmlContent); $revision = $this->Item->getLastRevision($itemDao); if ($revision === false) { throw new Zend_Exception('The item has no revisions', MIDAS_INVALID_POLICY); } $bitstreams = $revision->getBitstreams(); $itemRevisionDao = new ItemRevisionDao(); $itemRevisionDao->setChanges('Modification Definition File'); $itemRevisionDao->setUser_id($this->userSession->Dao->getKey()); $itemRevisionDao->setDate(date('Y-m-d H:i:s')); $itemRevisionDao->setLicenseId(null); $this->Item->addRevision($itemDao, $itemRevisionDao); foreach ($bitstreams as $b) { if ($b->getName() != 'MetaIO.vxml') { $b->saved = false; $b->setBitstreamId(null); $this->Bitstream->save($b); $this->ItemRevision->addBitstream($itemRevisionDao, $b); } } $bitstreamDao = new BitstreamDao(); $bitstreamDao->setName('MetaIO.vxml'); $bitstreamDao->setPath($pathFile); $bitstreamDao->fillPropertiesFromPath(); $assetstoreDao = $this->Assetstore->getDefault(); $bitstreamDao->setAssetstoreId($assetstoreDao->getKey()); // Upload the bitstream if necessary (based on the assetstore type) $this->Component->Upload->uploadBitstream($bitstreamDao, $assetstoreDao); $this->ItemRevision->addBitstream($itemRevisionDao, $bitstreamDao); if (file_exists($pathFile)) { unlink($pathFile); } } }