/** * Parse params from request. * @return array */ public function getParamsFromRequest() { $requestMethod = strtolower($_SERVER['REQUEST_METHOD']); switch ($requestMethod) { case 'get': $params = $_GET; break; case 'post': $params = $_POST; $xml = @simplexml_load_string($params['data']); if (false !== $xml && null !== $xml) { $params = XML2Array::createArray($params['data']); } break; case 'put': parse_str(file_get_contents('php://input'), $params); $xml = @simplexml_load_string($params['data']); if (false !== $xml && null !== $xml) { $params = XML2Array::createArray($params['data']); } $params['id'] = $_GET['id']; break; case 'delete': $params['id'] = $_GET['id']; break; } return $params; }
/** * @param string $xml - XML de resposta do Webservice */ function __construct($xml) { $array = XML2Array::createArray($xml); foreach ($array as $indice => $valor) { $this->array = $valor; switch ($indice) { case 'AUTHORIZATION': //GetAuthorized $this->retornoAutorizacao(); break; case 'CONFIRMATION': //vários casos $this->retornoConfirmacao(); break; case 'COUNCIL': //CouncilReport $this->retornoVendas(); break; case 'REPORT': //SalesSumm $this->retornoRelatorio(); break; case 'ROOT': //Erro no CouncilReport ou SalesSumm $this->retornoErro(); break; default: throw new \UnexpectedValueException('Retorno inesperado.'); } } unset($this->array); //o atributo não será mais utilizado }
private static function _xml2array($xml) { if (!$xml || $xml == "") { return array(); } require_once dirname(__FILE__) . "/xml2array.lib.class.php"; return XML2Array::createArray($xml); }
/** * Transforms the API response into a PHP array * * @static * @param $response * @param $format * @return array|mixed|DOMDocument */ public static function transform($response, $format) { if ($format == "json") { return json_decode($response); } elseif ($format == "xml") { return XML2Array::createArray($response); } else { throw new \Exception("{$format} transformer is not implemented yet"); } }
protected function login($username = '******', $password = '******', $type = 'json') { $headers = array('Accept: application/' . $type, 'ZURMO_AUTH_USERNAME: '******'ZURMO_AUTH_PASSWORD: '******'ZURMO_API_REQUEST_TYPE: REST'); $response = ApiRestTestHelper::createApiCall($this->serverUrl . '/test.php/zurmo/api/login', 'POST', $headers); if ($type == 'json') { $response = json_decode($response, true); } elseif ($type == 'xml') { $response = XML2Array::createArray($response); } if ($response['status'] == ApiResponse::STATUS_SUCCESS) { return $response['data']; } else { return false; } }
/** * Obtiene y limpia el JSON final para insertar el ebook como documento * Limpia y agrega los campos de _id y lastUpdate */ public static function getBookJSONFromXMLNode2($node) { //Funcion de procesamiento del XMl a la cadena JSON $arr = XML2Array::createArray($node); //Agrega last update y limpia el inicio y fin para simplificar la jerarquia //De esta forma no funciona al pasar a json se pierde //$arr['book']['lastUpdate'] = new MongoDate(); $date = new MongoDate(); $arr['book']['lastUpdate'] = array('$date' => $date->sec * 1000 + $date->usec / 1000); $mongo_id = str_replace('-', '', $arr['book']['@attributes']['id']); $arr['book']['_id'] = $mongo_id; //concvert to json $jsonContents = json_encode($arr); //Eliminación de datos innecesarios en la cadena JSON $json_string = Utils::cleanJSON($jsonContents); return $json_string; }
/** * getResponse function * This will get a detailed description from MedlinePlus Connect * @param $coding * @param $code * @return \Array */ function getResponse($coding, $code) { if ($coding == 'ICD9') { $this->codingSystem = 'mainSearchCriteria.v.cs=2.16.840.1.113883.6.103'; } if ($coding == 'SNOMED') { $this->codingSystem = 'mainSearchCriteria.v.cs=2.16.840.1.113883.6.96'; } if ($coding == 'RXCUI') { $this->codingSystem = 'mainSearchCriteria.v.cs=2.16.840.1.113883.6.88'; } if ($coding == 'NDC') { $this->codingSystem = 'mainSearchCriteria.v.cs=2.16.840.1.113883.6.69'; } if ($coding == 'LOINC') { $this->codingSystem = 'mainSearchCriteria.v.cs=2.16.840.1.113883.6.1'; } $urlBuilder = $this->medlineUrl . $this->codingSystem . '&mainSearchCriteria.v.c=' . $code; $xmlData = simplexml_load_file($urlBuilder); return \XML2Array::createArray($xmlData); }
function markers_deployable($res, $world) { $markers = array(); $xml = file_get_contents('vehicles.xml', true); require_once 'modules/lib/class.xml2array.php'; $vehicles_xml = XML2Array::createArray($xml); while ($row = mysql_fetch_array($res)) { $Worldspace = str_replace("[", "", $row['Worldspace']); $Worldspace = str_replace("]", "", $Worldspace); $Worldspace = explode(",", $Worldspace); $x = 0; if (array_key_exists(1, $Worldspace)) { $x = $Worldspace[1]; } $y = 0; if (array_key_exists(2, $Worldspace)) { $y = $Worldspace[2]; } $type = $row['Classname']; $ltype = strtolower($type); if (array_key_exists('s' . $ltype, $vehicles_xml['vehicles'])) { $class = $vehicles_xml['vehicles']['s' . $ltype]['Type']; } else { $class = "Car"; } require_once 'modules/calc.php'; $description = '<h2><a href="index.php?view=info&show=5&id=' . $row['ObjectID'] . '">' . $type . '</a></h2><table><tr><td><img src="images/vehicles/' . $ltype . '.png" alt="" style="width: 100px;" /></td><td> </td><td style="vertical-align: top;"><h2>Position:</h2>Left: ' . round(world_x($x, $world)) . '<br />Top: ' . round(world_y($y, $world)) . '</td></tr></table>'; $tmp = array(); $tmp["lat"] = world_y($y, $world) / 10; $tmp["lng"] = world_x($x, $world) / 10; $tmp["icon"] = $class; $tmp["title"] = $type . " (" . $row['ObjectID'] . ")"; $tmp["description"] = $description; $markers[] = $tmp; } return $markers; }
for ($i = 1; $i <= $pages; $i++) { print_r("page " . $i . "\n"); $cases = XML2Array::createArray($ebay->getCases(200, $i)); $cases = isset($cases["soapenv:Envelope"]["soapenv:Body"]["getUserCasesResponse"]["cases"]["caseSummary"]) ? $cases["soapenv:Envelope"]["soapenv:Body"]["getUserCasesResponse"]["cases"]["caseSummary"] : array(); if (!empty($cases)) { print_r("cases: " . count($cases) . "\n"); foreach ($cases as $j => $caseShort) { if (isset($caseShort['user']) && $caseShort['user']['userId'] == "chandlermotorsportsinc" && $caseShort['user']['role'] == "SELLER") { $sql = "SELECT * FROM cases where caseId = '" . $caseShort['caseId']['id'] . "'"; $rs = $db->Execute($sql); $row = $rs->FetchRow(); if (isset($row['caseId'])) { print_r("case: " . $row['caseId'] . " exists" . "\n"); continue; } $case = XML2Array::createArray($ebay->getCaseDetails($caseShort['caseId']['id'], $caseShort['caseId']['type'])); $case = isset($case["soapenv:Envelope"]["soapenv:Body"]["getEBPCaseDetailResponse"]) ? $case["soapenv:Envelope"]["soapenv:Body"]["getEBPCaseDetailResponse"] : array(); if (!isset($case['caseSummary']['caseId']['id'])) { $caseSummary = $caseShort; $caseDetail = array(); } else { $caseSummary = $case['caseSummary']; $caseDetail = isset($case['caseDetail']) ? $case['caseDetail'] : array(); } $status = isset($caseSummary['status']) ? array_values($caseSummary['status']) : array(); $tmp = array("caseId" => $caseSummary['caseId']['id'], "type" => isset($caseSummary['caseId']['type']) ? $caseSummary['caseId']['type'] : '', "userId" => isset($caseSummary['otherParty']['userId']) ? $caseSummary['otherParty']['userId'] : '', "status" => isset($status[0]) ? $status[0] : '', "itemId" => isset($caseSummary['item']['itemId']) ? $caseSummary['item']['itemId'] : '', "transactionId" => isset($caseSummary['item']['transactionId']) ? $caseSummary['item']['transactionId'] : '', "respondByDate" => isset($caseSummary["respondByDate"]) ? $caseSummary["respondByDate"] : '', "creationDate" => isset($caseSummary["creationDate"]) ? $caseSummary["creationDate"] : '', "lastModifiedDate" => isset($caseSummary["lastModifiedDate"]) ? $caseSummary["lastModifiedDate"] : '', "openReason" => isset($caseDetail["openReason"]) ? $caseDetail["openReason"] : '', "decision" => isset($caseDetail["decision"]) ? $caseDetail["decision"] : '', "agreedRefundAmount" => isset($caseDetail["agreedRefundAmount"]) ? $caseDetail["agreedRefundAmount"] : '', "detailStatus" => isset($caseDetail["detailStatus"]) ? $caseDetail["detailStatus"] : '', "initialBuyerExpectation" => isset($caseDetail["initialBuyerExpectation"]) ? $caseDetail["initialBuyerExpectation"] : ''); $updateSQL = $db->GetInsertSQL($rs, $tmp); $db->Execute($updateSQL); } } } else {
/** * XML 복원파일을 입력받아 기존 데이터를 비우고 DB에 입력한다. * @param string $file */ public function importXml($file) { global $wpdb; include 'XML2Array.class.php'; $xml = file_get_contents($file); $array = XML2Array::createArray($xml); foreach ($array['kboard'] as $table => $rows) { // 테이블에 입력될 데이터가 한 개인지 여러개 인지 확인한다. if (isset($rows['data']) && is_array($rows['data'])) { $keys = array_keys($rows['data']); if (reset($keys) == '0') { $data = $rows['data']; } else { $data = $rows; } } else { $data = $rows; } if ($data) { // 테이블 이름에 PREFIX를 추가 한다. $table = $wpdb->prefix . $table; // 새로 생성될 테이블을 비운다. $wpdb->query("TRUNCATE TABLE `{$table}`"); // 새로운 content를 입력하기 위해서 posts테이블에 입력된 content를 삭제한다. if (stristr($table, 'kboard_board_content')) { $wpdb->query("DELETE FROM `{$wpdb->prefix}posts` WHERE `post_type`='kboard'"); } foreach ($data as $key => $row) { $keys = array_keys($row); $row_count = count($row); $columns = array(); for ($i = 0; $i < $row_count; $i++) { $columns[] = "`{$keys[$i]}`"; } $columns = implode(',', $columns); $value = array(); for ($i = 0; $i < $row_count; $i++) { $value[] = "'" . addslashes($row[$keys[$i]]['@cdata']) . "'"; } $value = implode(',', $value); $wpdb->query("INSERT INTO `{$table}` ({$columns}) VALUE ({$value})"); /* * search 값이 있을경우 post 테이블에 내용을 입력한다. */ if (isset($row['search']) && ($row['search']['@cdata'] == 1 || $row['search']['@cdata'] == 2)) { if ($wpdb->insert_id) { $kboard_post = array('post_author' => $row['member_uid']['@cdata'], 'post_title' => addslashes($row['title']['@cdata']), 'post_content' => addslashes($row['secret']['@cdata'] == 'true' || $row['search']['@cdata'] == 2 ? '' : $row['content']['@cdata']), 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_name' => $wpdb->insert_id, 'post_parent' => $row['board_id']['@cdata'], 'post_type' => 'kboard'); wp_insert_post($kboard_post, true); } } } // end foreach } } // end foreach }
/** * @param string $prj_id * @return array * @throws AException */ public function getProjectConfig($prj_id) { $file_name = DIR_EXT . 'developer_tools/projects/dev_tools_project_' . $prj_id . '.xml'; $xml = file_get_contents($file_name); $xml_array = array(); if ($xml) { $xml_array = XML2Array::createArray($xml); if (!$xml_array) { $this->error[] = 'Cannot convert xml-file ' . $file_name . ' into array. Probably wrong xml syntax.'; } $xml_array = $xml_array['project']['extension']; foreach ($xml_array as &$node) { if (is_array($node) && isset($node['@cdata'])) { $node = $node['@cdata']; } } // remove item tag from arrays $mvcs = array('models', 'views', 'controllers', 'languages'); foreach ($this->sections as $section) { foreach ($mvcs as $mvc) { $item = $xml_array[$mvc][$section]['item']; if (is_array($item) && is_string(key($item))) { $item = array($item); } $xml_array[$mvc][$section] = $item; } } } else { $this->error[] = 'Cannot open file ' . $file_name; } return $xml_array; }
<?php if (isset($_SESSION['user_id'])) { ini_set("display_errors", 0); error_reporting(E_ALL ^ E_NOTICE); $pagetitle = "Dashboard"; $logs = ""; $res = $db->GetAll("SELECT * FROM `logs` ORDER BY `timestamp` DESC LIMIT 100"); foreach ($res as $row) { $logs .= $row['timestamp'] . ' ' . $row['user'] . ': ' . $row['action'] . chr(13); } $xml = file_get_contents('quicklinks.xml', true); require_once 'xml2array.php'; $quicklinks = XML2Array::createArray($xml); if (isset($_GET['chat'])) { $chat_view = 'chat'; } if (isset($_GET['logs'])) { $chat_view = 'logs'; } if (!isset($_GET['logs']) && !isset($_GET['chat'])) { $chat_view = 'logs'; } ?> <div id="page-heading"> <?php echo "<title>" . $pagetitle . " - " . $sitename . "</title>"; echo "<h1>" . $pagetitle . "</h1>"; ?> </div>
foreach ($arr['CommonFormat']['Section'] as $n => $spot) { if (!empty($spot['xbody'])) { $mid = 'tpe-spot-q00-' . $n; $mongo->kg->update(array('id' => $mid), array('id' => $mid, 'cat' => 'travel', 'q' => '位於' . $spot['address'] . ' 的 ' . $spot['stitle'] . " 有何特色?", 'a' => $spot['xbody'], 'ts_c' => time(), 'ts_v' => 0, 'img' => empty($spot['file']['img'][0]['@value']) ? null : $spot['file']['img'][0]['@value'], 'location' => empty($spot['latitude']) ? null : array('lat' => $spot['latitude'], 'lon' => $spot['longitude']), 'url' => empty($spot['xurl']) ? null : $spot['xurl']), array('upsert' => true)); } if (!empty($spot['info'])) { $mid = 'tpe-spot-q01-' . $n; $mongo->kg->update(array('id' => $mid), array('id' => $mid, 'cat' => 'travel', 'q' => '位於' . $spot['address'] . ' 的 ' . $spot['stitle'] . " 該如何前往?", 'a' => $spot['info'], 'ts_c' => time(), 'ts_v' => 0, 'img' => empty($spot['file']['img'][0]['@value']) ? null : $spot['file']['img'][0]['@value'], 'location' => empty($spot['latitude']) ? null : array('lat' => $spot['latitude'], 'lon' => $spot['longitude']), 'url' => empty($spot['xurl']) ? null : $spot['xurl']), array('upsert' => true)); } if (!empty($spot['MEMO_TIME'])) { $mid = 'tpe-spot-q02-' . $n; $mongo->kg->update(array('id' => $mid), array('id' => $mid, 'cat' => 'travel', 'q' => '位於' . $spot['address'] . ' 的 ' . $spot['stitle'] . " 開放時間為何?", 'a' => $spot['MEMO_TIME'], 'ts_c' => time(), 'ts_v' => 0, 'img' => empty($spot['file']['img'][0]['@value']) ? null : $spot['file']['img'][0]['@value'], 'location' => empty($spot['latitude']) ? null : array('lat' => $spot['latitude'], 'lon' => $spot['longitude']), 'url' => empty($spot['xurl']) ? null : $spot['xurl']), array('upsert' => true)); } } ///////////////////////////// $arr = XML2Array::createArray(file_get_contents('dataset/taipei/travelStayCHINESE.xml')); foreach ($arr['CommonFormat']['Section'] as $n => $spot) { if (!empty($spot['xbody']) && !empty($spot['address'])) { $mid = 'tpe-hotel-q00-' . $n; $mongo->kg->update(array('id' => $mid), array('id' => $mid, 'cat' => 'travel', 'q' => '位於' . $spot['address'] . ' 的 ' . $spot['stitle'] . " 有何特色?", 'a' => $spot['xbody'], 'ts_c' => time(), 'ts_v' => 0, 'img' => empty($spot['file']['img'][0]['@value']) ? null : $spot['file']['img'][0]['@value'], 'location' => empty($spot['latitude']) ? null : array('lat' => $spot['latitude'], 'lon' => $spot['longitude']), 'url' => empty($spot['xurl']) ? null : $spot['xurl']), array('upsert' => true)); } if (!empty($spot['MEMO_COST'])) { $mid = 'tpe-hotel-q01-' . $n; $mongo->kg->update(array('id' => $mid), array('id' => $mid, 'cat' => 'travel', 'q' => '位於' . $spot['address'] . ' 的 ' . $spot['stitle'] . " 價位為何?", 'a' => $spot['MEMO_COST'], 'ts_c' => time(), 'ts_v' => 0, 'img' => empty($spot['file']['img'][0]['@value']) ? null : $spot['file']['img'][0]['@value'], 'location' => empty($spot['latitude']) ? null : array('lat' => $spot['latitude'], 'lon' => $spot['longitude']), 'url' => empty($spot['xurl']) ? null : $spot['xurl']), array('upsert' => true)); } } ///////////////////////////// $arr = file('dataset/taipei/臺北市104年度颱風期間開放停車學校概況一覽表.txt'); $schools = array(); $n = 0; foreach ($arr as $line) {
<?php require_once 'config.php'; require_once 'lib/ebay.php'; require_once 'lib/cUrl.php'; require_once 'lib/xml.php'; require_once 'lib/imagemagick.class.php'; $ebay = new Ebay($ebayDEVID, $ebayAppID, $ebayCertID, $ebayToken); $fbNumber = isset($_GET['number']) ? (int) $_GET['number'] : 5; $feedbacks = XML2Array::createArray($ebay->getFeedBacks($fbNumber)); $feedbacks = isset($feedbacks["GetFeedbackResponse"]['FeedbackDetailArray']['FeedbackDetail']) ? $feedbacks["GetFeedbackResponse"]['FeedbackDetailArray']['FeedbackDetail'] : array(); if (empty($feedbacks)) { print_r('error'); exit; } ImageMagick::deleteOldFiles(TEXT_TOOL_TMP_PATH); $feedbackImages = array(); foreach ($feedbacks as $feedback) { $texts = array("str1" => $feedback['CommentText'] . ', ' . date('M-d-y H:i', strtotime($feedback['CommentTime'])), "str2" => $feedback['CommentingUser'] . ' (' . $feedback['CommentingUserScore'] . ')', "str3" => ' ' . $feedback['ItemTitle'] . ' (#' . $feedback['ItemID'] . ')'); $textImages = array(); foreach ($texts as $name => $text) { $textData = array('font' => "Arial", 'text' => $text, 'size' => 16, 'color' => "black", 'rotate' => 0); if ($name == 'str3') { $textData['color'] = "gray"; } $textImages[$name] = ImageMagick::createText($textData); } ImageMagick::addPlus($textImages['str1']); ImageMagick::addStar($textImages['str2'], $feedback['CommentingUserScore']); ImageMagick::addBorder(TEXT_TOOL_TEXT_PATH . $textImages['str1'], 3); ImageMagick::addBorder(TEXT_TOOL_TEXT_PATH . $textImages['str2'], 3);
function parse_xml_result($result, $xml) { $data = XML2Array::createArray($xml); //print_r($xml); // print_r($data['factapi']); if (isset($data['factapi']['control']['num_journals']) and $data['factapi']['control']['num_journals'] == 1) { $result['journal']['issn'] = $data['factapi']['journallist']['journal']['@attributes']['issn']; $result['journal']['title'] = $data['factapi']['journallist']['journal']['title']; $result['result_type'] = 'Ok'; } else { $result['result_type'] = 'Error'; } if (isset($data['factapi']['gold']['goldcompliance'])) { switch ($data['factapi']['gold']['goldcompliance']['@attributes']['goldcompliancecode']) { case 'yes': $result['gold']['code'] = 'Yes'; $result['compilance_type'] = 'Gold'; break; case 'no': $result['gold']['code'] = 'No'; break; case 'maybe': $result['gold']['code'] = 'Maybe'; break; case 'unknown': $result['gold']['code'] = 'Unknown'; break; default: $result['gold']['code'] = $data['factapi']['gold']['goldcompliance']['@attributes']['goldcompliancecode']; } $result['gold']['report'] = $data['factapi']['gold']['goldcompliance']['@attributes']['goldcompliancereport']; if (is_array($data['factapi']['gold']['goldreason']) and isset($data['factapi']['gold']['goldreason']['@value'])) { $result['gold']['reason'] = $data['factapi']['gold']['goldreason']['@value']; } else { $result['gold']['reason'] = $data['factapi']['gold']['goldreason']; } if (isset($data['factapi']['gold']['goldadvicelist']['goldadvice']['@value'])) { $result['gold']['advice'] = $data['factapi']['gold']['goldadvicelist']['goldadvice']['@value']; } } if (isset($data['factapi']['green']['greencompliance'])) { switch ($data['factapi']['green']['greencompliance']['@attributes']['greencompliancecode']) { case 'yes': $result['green']['code'] = 'Yes'; if ($result['compilance_type'] == 'Gold') { $result['compilance_type'] = 'GreenGold'; } else { $result['compilance_type'] = 'Green'; } break; case 'no': $result['green']['code'] = 'No'; break; case 'maybe': $result['green']['code'] = 'Maybe'; break; case 'unknown': $result['green']['code'] = 'Unknown'; break; default: $result['green']['code'] = $data['factapi']['green']['greencompliance']['@attributes']['greencompliancecode']; } $result['green']['report'] = $data['factapi']['green']['greencompliance']['@attributes']['greencompliancereport']; if (is_array($data['factapi']['green']['greenreason']) and isset($data['factapi']['green']['greenreason']['@value'])) { $result['green']['reason'] = $data['factapi']['green']['greenreason']['@value']; } else { $result['green']['reason'] = $data['factapi']['green']['greenreason']; } if (isset($data['factapi']['green']['greenadvicelist']['greenadvice']['@value'])) { $result['green']['advice'] = $data['factapi']['green']['greenadvicelist']['greenadvice']['@value']; } } if (isset($data['factapi']['overall']['overallcompliance'])) { switch ($data['factapi']['overall']['overallcompliance']['@attributes']['overallcompliancecode']) { case 'yes': $result['compilance'] = 'Yes'; break; case 'no': $result['compilance'] = 'No'; break; case 'maybe': $result['compilance'] = 'Maybe'; break; case 'unknown': $result['compilance'] = 'Unknown'; break; default: $result['compilance'] = $data['factapi']['overall']['overallcompliance']['@attributes']['goldcompliancecode']; } $result['compilance_report'] = $data['factapi']['overall']['overallcompliance']['@attributes']['overallcompliancereport']; } return $result; }
/** * @param $xml * @return DOMDocument */ function XmlToArray($xml) { return XML2Array::createArray($xml); }
function geocode_addr($addr) { /* if($_SERVER['REMOTE_ADDR']=='192.168.6.12') { echo $addr; die; }*/ $result = file_get_contents('http://geocode-maps.yandex.ru/1.x/?geocode=' . $addr_obl . ',' . $addr . '&results=1'); //echo 'http://geocode-maps.yandex.ru/1.x/?geocode=Кемеровская область,'.$addr.'&results=1'; $array = XML2Array::createArray($result); //echo '<pre>'; //print_r($result); //print_r($array['ymaps']['GeoObjectCollection']['featureMember'][0]['GeoObject']['name']); //return $array['ymaps']['GeoObjectCollection']['featureMember'][0]['GeoObject']['name']; //die; if ($array['ymaps']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found']) { $LonLat = explode(" ", $array['ymaps']['GeoObjectCollection']['featureMember']['GeoObject']['Point']['pos']); echo 'var lon=' . $LonLat['0'] . '; var lat=' . $LonLat['1'] . ';'; //echo '</pre>'; } die; }
<?php require_once 'config.php'; require_once 'lib/ebay.php'; require_once 'lib/cUrl.php'; require_once 'lib/xml.php'; $ebay = new Ebay($ebayDEVID, $ebayAppID, $ebayCertID, $ebayToken); $cases = XML2Array::createArray($ebay->getCases(100)); print_r($cases["soapenv:Envelope"]["soapenv:Body"]["getUserCasesResponse"]['cases']["caseSummary"]); exit; //$case = XML2Array::createArray($ebay->getCaseDetails(562217998, "PAYPAL_SNAD")); print_r($case["soapenv:Envelope"]["soapenv:Body"]["getEBPCaseDetailResponse"]);
$xmlDestino2 = $_SESSION['workfolder_webdir'] . "Destacados.xml"; $fp = fopen($xmlDestino2, 'w'); fwrite($fp, $xmlString); fclose($fp); } /*$xml = simplexml_load_file($xmlDestino, 'SimpleXMLElement',LIBXML_NOCDATA); $json = json_encode($xml); $XMLarray = json_decode($json,TRUE); krumo($XMLarray);*/ $xml = file_get_contents($xmlDestino); // por lo visto es mejor iconv si el texto puede contener caracteres como € que no estan en utf_decode //$xml=iconv("UTF-8", "ISO-8859-1//TRANSLIT", $xml); // utf8_decode para los caracteres especiales, ñ y demás $xml = utf8_decode($xml); // cargamos el XML Destacados y lo transformamos en un Array para poder crear el formulario $destacadosArray = XML2Array::createArray($xml); $formulario = buildDestacadosForm($destacadosArray); //krumo($destacadosArray); // http://cruzroja.vivocomtech.net/Destacados.xml // construir formulario function buildDestacadosForm($xmlArray) { //krumo($xmlArray); $baseNode = $xmlArray['Destacados']['Destacado']; //krumo(count($baseNode)); $form = new PhpFormBuilder(); $form->set_att('enctype', 'multipart/form-data'); $form->set_att('method', 'post'); $form->set_att('id', 'cr_xml_edit'); $count = 1; foreach ($baseNode as $int => $value) {
echo '<script type="text/javascript">window.location = "index.php?view=table&show=5"</script>'; } //$res = mysql_query("SELECT deployable.class_name, instance_deployable.* FROM `deployable`, `instance_deployable` WHERE deployable.id = instance_deployable.deployable_id AND instance_deployable.id = '".$_GET["id"]."' LIMIT 1") or die(mysql_error()); $res = mysql_query("\nSELECT object_data.* FROM `object_data` \nWHERE object_data.Instance = '" . $serverinstance . "' \nAND ObjectID = '" . $_GET["id"] . "' LIMIT 1") or die(mysql_error()); $row = mysql_fetch_assoc($res); $Worldspace = str_replace("[", "", $row['Worldspace']); $Worldspace = str_replace("]", "", $Worldspace); $Worldspace = explode(",", $Worldspace); $Deployable = $row['Inventory']; $Deployable = json_decode($Deployable); $xml = file_get_contents('items.xml', true); require_once 'modules/lib/class.xml2array.php'; $items_xml = XML2Array::createArray($xml); $xml = file_get_contents('vehicles.xml', true); require_once 'modules/lib/class.xml2array.php'; $vehicles_xml = XML2Array::createArray($xml); ?> <div id="page-heading"> <title><?php echo $row['Classname'] . " - " . $sitename; ?> </title> <h1><?php echo $row['Classname'] . " - " . $row['ObjectUID'] . " - Last save: " . $row['Datestamp'] . " - Position: " . $row['Worldspace']; ?> </h1> </div> <table id="content-table" border="0" width="100%" cellpadding="0" cellspacing="0"> <tr>
<?php require_once 'config.php'; require_once 'lib/ebay.php'; require_once 'lib/cUrl.php'; require_once 'lib/xml.php'; $pages = 500; $ebay = new Ebay($ebayDEVID, $ebayAppID, $ebayCertID, $ebayToken); $allFeedbacks = array(); $header = array("CommentingUser", "CommentingUserScore", "CommentText", "CommentTime", "CommentType", "ItemID", "Role", "FeedbackID", "TransactionID", "OrderLineItemID", "ItemTitle", "ItemPrice", "currencyID"); for ($i = 1; $i <= $pages; $i++) { print_r($i); $feedbacks = XML2Array::createArray($ebay->getFeedBacks(200, $i)); $feedbacks = isset($feedbacks["GetFeedbackResponse"]['FeedbackDetailArray']['FeedbackDetail']) ? $feedbacks["GetFeedbackResponse"]['FeedbackDetailArray']['FeedbackDetail'] : array(); if (!empty($feedbacks)) { foreach ($feedbacks as $j => $feedback) { if (isset($feedback['ItemPrice'])) { $feedbacks[$j]['ItemPrice'] = $feedback['ItemPrice']['@value']; $feedbacks[$j]['currencyID'] = $feedback['ItemPrice']['@attributes']['currencyID']; } $tmp = array(); foreach ($header as $key) { $tmp[$key] = isset($feedbacks[$j][$key]) ? $feedbacks[$j][$key] : ''; } $sql = "SELECT * FROM feedbacks where FeedbackID = {$tmp['FeedbackID']}"; $rs = $db->Execute($sql); $row = $rs->FetchRow(); if (isset($row['FeedbackID'])) { exit; } $updateSQL = $db->GetInsertSQL($rs, $tmp);
public function getResponseBodyArray($response) { return $re = XML2Array::createArray($response->body); }
if ($in) { $prov['cfg_behavior'] = array_merge($prov['cfg_behavior'], XML2Array::createArray($in)); } $in = ''; if ($in) { $prov['cfg_base'] = XML2Array::createArray($in); } /* if you have more the 1 subselection add this seperatly */ $in = ''; if ($in) { $prov['cfg_base'] = array_merge($prov['cfg_base'], XML2Array::createArray($in)); } $in = ''; if ($in) { $prov['cfg_base'] = array_merge($prov['cfg_base'], XML2Array::createArray($in)); } $in = ''; if ($in) { $prov['cfg_tone'] = XML2Array::createArray($in); } $in = ''; if ($in) { $prov['cfg_keys'] = XML2Array::createArray($in); } $prov['cfg_key'] = json_decode(plain2json($in, $del)); $prov['pvt_generator'] = 'json2xml'; $prov['pvt_counter'] = 1; $prov['pvt_type'] = 'provisioner'; echo upload_phone_data($prov); unset($prov); }
$RawInventory = $row['Inventory']; $Inventory = json_decode($RawInventory); $RawBackpack = $row['Backpack']; $Backpack = json_decode($RawBackpack); $model = str_replace('"', '', $row['Model']); $name = $row['PlayerName']; if (is_array($Inventory)) { if (array_key_exists(1, $Inventory)) { $Inventory = array_merge($Inventory[0], $Inventory[1]); } } else { $Inventory = array(); } $xml = file_get_contents('/items.xml', true); require_once 'modules/lib/class.xml2array.php'; $items_xml = XML2Array::createArray($xml); if (file_exists('banned.txt')) { $txt = file_get_contents('banned.txt', true); $txt = str_replace("\"", "", str_replace("\r", "", $txt)); $items_banned = explode("\n", $txt); } else { $items_banned = array(); } $binocular = array(); $rifle = '<img style="max-width: 220px; max-height: 92px;" src="images/gear/rifle.png" title="" alt="" />'; $pistol = '<img style="max-width: 92px; max-height: 92px;" src="images/gear/pistol.png" title="" alt="" />'; $second = '<img style="max-width: 220px; max-height: 92px;" src="images/gear/second.png" title="" alt="" />'; $heavyammo = array(); $heavyammoslots = 0; $smallammo = array(); $usableitems = array();
function translateOneNode($currentNodeID, $to_languages, $content_type) { global $db, $XMLarray, $error_log; $separator = "7543545165934149"; // Fetch a node from Drupal if a copy does not already exist in sources dir. // $xml_MASTER is the original English-language version // $xml is the copy that will be translated $fn = getcwd() . "/sources/SOURCE_" . $currentNodeID . ".XML"; if (file_exists($fn)) { $xml_MASTER = file_get_contents($fn); if ($content_type == "page") { // Remove <teaser> from "page". The "teaser" is created by truncating the <body>, resulting in invalid XML $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER); } } else { $xml_MASTER = fetchOneNode($currentNodeID); if ($content_type == "page") { $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER); } $fh = fopen($fn, "w"); fwrite($fh, $xml_MASTER); fclose($fh); } foreach ($to_languages as $to_language) { $query = "select drupal_code from sovee.languages where sovee_code = '" . $to_language . "'"; $result = mysql_query($query, $db); while ($row = mysql_fetch_assoc($result)) { $drupalLanguageCode = $row['drupal_code']; } mysql_free_result($result); echo "\n=====================================================================================\n========== ==========\n. . . Translating node {$currentNodeID} ({$content_type}) into {$to_language} . . . \n"; $error_IncompleteNodeFlag = 0; $xml = $xml_MASTER; // Create a copy of the master, to be translated // Convert XML to array $XMLarray = XML2Array::createArray($xml); // Get info about the node // Requested info is placed in the $requestedTags array // and returned in the assoc. array info() $requestedTags = array("type", "tnid"); $info = getXMLinfo($xml, $requestedTags); $derivedContentType = $info['type']; // Build list of containers to parse for the given content_type. $query = "select DISTINCT sovee.node_fields.name from sovee.content_type \nLEFT JOIN sovee.field_map ON sovee.content_type.id = sovee.field_map.content_id\nLEFT JOIN sovee.node_fields ON sovee.node_fields.id = sovee.field_map.field_id\nWHERE sovee.content_type.name = '" . $derivedContentType . "'"; $result = mysql_query($query, $db); while ($row = mysql_fetch_assoc($result)) { $containerArrayTemplate[] = $row['name']; } mysql_free_result($result); // Walk throught the array, extract the specified containers, translate // and replace in the array // All array elements are assumed to be in the [node_export][node] array // $containerArrayTemplate = array("body", "title", "teaser", "field_product_subtitle|n*|value", "field_warranty|n*|value", "field_product_education|n*|value", // "field_prod_man_docs_link|n*|title", // "field_did_you_know|n*|value", "field_product_benefits|n*|value", "nodewords|copyright|value", "nodewords|dcterms.contributor|value", // "nodewords|dcterms.title|value", "nodewords|description|value", "nodewords|keywords|value" ); $containerArray = expandTemplate($containerArrayTemplate); $allContainers = "<div>{$separator}"; foreach ($containerArray as $oneContainer) { echo "\nProcessing container {$oneContainer}\n"; $parents = explode("|", $oneContainer); array_unshift($parents, "node_export", "node"); #echo "Parents: "; #print_r($parents); $XMLfragment = drupal_array_get_nested_value($XMLarray, $parents); if (is_array($XMLfragment)) { $XMLfragment = ""; } $translatedFragment = ""; $patterns = array("|^<div>|us", "|</div>\$|us"); // The "|u" flag enables multibyte support $replacements = array("", ""); if (strlen(trim($XMLfragment)) > 0 and !is_array($XMLfragment)) { $XMLfragment = "<div>" . $XMLfragment . "</div>"; // Encapsulate in dummy <div> to satisfy Sovee translator // echo "ORIGINAL Fragment = |$XMLfragment|\n"; } else { echo "Original Fragment |{$XMLfragment}| is empty -- skipping.\n"; } $allContainers .= $XMLfragment . $separator; // Add at the end of each container to faciliate preg_split } // ------- End of foreach($containerArray as $oneContainer) $allContainers .= "</div>"; // Translate the entire node if target language is not English echo "TO_LANGUAGE = {$to_language}\n"; $xxx = substr($to_language, 0, 2); echo "SUBSTR = |{$xxx}|\n"; $sovee_to_language = $to_language; if (substr($to_language, 0, 2) != "en") { if ($to_language == "es-419") { $sovee_to_language = "es-es"; } // Use standard Spanish for Latin America echo "Sending strings to Sovee . . . \n"; $translatedFragmentAry = translateFrag($allContainers, $currentNodeID, "FULL NODE", $to_language); // Perform the translation $translatedFragment = $translatedFragmentAry['content']; $translatedFragmentError = $translatedFragmentAry['error_count']; // Count of translation errors. 0 = success $error_IncompleteNodeFlag += $translatedFragmentError; } else { echo "English-to-English: No translation needed.\n"; $translatedFragment = $allContainers; $translatedFragmentError = 0; } // print_r($translatedFragmentAry); $separatorPattern = "/{$separator}/u"; $translatedNodeAry = preg_split($separatorPattern, $translatedFragment); // print_r($translatedNodeAry); $translatedContentPointer = 1; reset($containerArray); foreach ($containerArray as $oneContainer) { $parents = explode("|", $oneContainer); array_unshift($parents, "node_export", "node"); $stripped = trim(preg_replace($patterns, $replacements, $translatedNodeAry[$translatedContentPointer])); // Remove the leading and trailing <div>s from the node fragments // Special handling for page_title, which can be a string or an array if ($oneContainer == "page_title" and $stripped == "Array") { $pageTitleParents1 = array('node_export', 'node', 'page_title', 'value'); $pageTitleParents2 = array('node_export', 'node', 'page_title', 'attributes', 'type'); drupal_array_set_nested_value($XMLarray, $pageTitleParents1, "FALSE"); drupal_array_set_nested_value($XMLarray, $pageTitleParents2, "boolean"); } else { if (strlen($stripped) > 0) { drupal_array_set_nested_value($XMLarray, $parents, $stripped); } } $translatedContentPointer++; } // HTML-Encode any info in the <data> container // $dataParents = array('node_export', 'node', 'data'); // $dataFragment = htmlentities(drupal_array_get_nested_value($XMLarray, $dataParents)); // drupal_array_set_nested_value($XMLarray, $dataParents, $dataFragment); #echo "TRANSLATED XML ARRAY:"; #print_r($XMLarray); // Does an older version of this translated node exist? // If yes, return the node# and alias in an array // otherwise, $oldNodeID_ary['number'] == '' $oldNodeID_ary = findOldTranslation($currentNodeID, $to_language); $oldNodeID = $oldNodeID_ary['number']; $oldNodeIDalias = $oldNodeID_ary['url_alias']; if ($oldNodeID != "") { echo "\nFound old node number -- old={$oldNodeID}\n"; } if ($oldNodeIDalias != "") { echo "\nFound old node number alias -- old={$oldNodeIDalias}\n"; } // Update the nid and tnid fields // For new nodes, nid='' // and tnid = the current nid value $XMLarray['node_export']['node']['tnid'] = $currentNodeID; $XMLarray['node_export']['node']['nid'] = $oldNodeID; // $XMLarray['node_export']['node']['language'] = $oldNodeID['drupal_lang_code']; $XMLarray['node_export']['node']['language'] = $drupalLanguageCode; // // // $XMLarray['node_export']['node']['path'] = $oldNodeID['url_alias']; if (isset($XMLarray['node_export']['node']['xmlsitemap']['language'])) { // $XMLarray['node_export']['node']['xmlsitemap']['language'] = $oldNodeID['drupal_lang_code']; $XMLarray['node_export']['node']['xmlsitemap']['language'] = $drupalLanguageCode; } //echo "XMLARRAY = \n"; //print_r($XMLarray); $FOO = $XMLarray['node_export']['node']['nodewords']['location']['latitude']; $BAR = $XMLarray['node_export']['node']['nodewords']['location']['longitude']; echo "FOO = {$FOO}\nBAR = {$BAR}\n"; // If lat or long > 8 chars, set to zero, otherwise node will not import if (isset($XMLarray['node_export']['node']['nodewords']['location']['latitude'])) { if (strlen($XMLarray['node_export']['node']['nodewords']['location']['latitude']) > 8) { $XMLarray['node_export']['node']['nodewords']['location']['latitude'] = 0; } } if (isset($XMLarray['node_export']['node']['nodewords']['location']['longitude'])) { if (strlen($XMLarray['node_export']['node']['nodewords']['location']['longitude']) > 8) { $XMLarray['node_export']['node']['nodewords']['location']['longitude'] = 0; } } // Adjust the menu references $this_plid = $XMLarray['node_export']['node']['menu']['plid']; $this_menu_name = $XMLarray['node_export']['node']['menu']['menu_name']; if ($this_menu_name == "primary-links") { $mquery = "SELECT t_menuid from sovee.menus LEFT JOIN sovee.languages on sovee.menus.language_code = sovee.languages.id WHERE drupal_code = \"" . $drupalLanguageCode . "\" and Eng_menuid = \"" . $this_plid . "\""; echo "MQ = {$mquery}\n"; $rmquery = mysql_query($mquery, $db); $err_msg = trim(mysql_error($db)); if (strlen($err_msg) > 0) { echo "{$mquery}\n{$err_msg}\n\n\n"; } while ($m1 = mysql_fetch_assoc($rmquery)) { $newPlid = $m1['t_menuid']; $XMLarray['node_export']['node']['menu']['plid'] = $newPlid; } mysql_free_result($rmquery); } // Convert array back to XML $encoding = "UTF-8"; $xmlVersion = "1.0"; Array2XML::init($xmlVersion, $encoding); $xmlobj = Array2XML::createXML('DELETE_ME', $XMLarray); // Convert a PHP array to XML, using 'DELETE_ME' as the root_node_name $translated_xml = $xmlobj->saveXML(); // Returned object is of type DOMDocument $translated_xml = preg_replace("/<[\\/]?DELETE_ME>[\n]/u", "", $translated_xml); $fn = getcwd() . "/TRANSLATED_" . $drupalLanguageCode . "_" . $currentNodeID . ".XML"; echo "WRITING {$fn}\n"; $fh = fopen($fn, "w"); fwrite($fh, $translated_xml); fclose($fh); // If node translation was successful, // import the translated node back into Drupal if ($error_IncompleteNodeFlag == 0) { $cmd = "/usr/bin/drush --root=/var/www/pressflow node-export-import --file={$fn}"; echo "COMMAND = {$cmd}\n"; $success = `{$cmd}`; $error = "DRUSH IMPORT RESULTS: {$success}\n"; echo $error; fwrite($error_log, $error); $cmd = "/bin/rm {$fn}"; #$success = `$cmd`; $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"1\", \"" . $derivedContentType . "\", \"" . $to_language . "\") ON DUPLICATE KEY UPDATE status=VALUES(status)"; echo "Q1={$q1}\n"; $r1 = mysql_query($q1, $db); } else { $error = "Node {$currentNodeID} ({$content_type}) not completely translated. Not importing into Drupal.\n"; echo $error; $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"0\", \"" . $derivedContentType . "\", \"" . $to_language . "\") ON DUPLICATE KEY UPDATE status=VALUES(status)"; $r1 = mysql_query($q1, $db); $err_msg = trim(mysql_error($db)); if (strlen($err_msg) > 0) { echo "{$q1}\n{$err_msg}\n\n\n"; } fwrite($error_log, $error); } echo "========== ==========\n=====================================================================================\n"; } $translated_xml_array = array('status' => $error_IncompleteNodeFlag, 'translated_xml' => $translated_xml); return $translated_xml_array; }
public function testNotAllowedGuestAction() { $authenticationData = $this->login('st', 'st'); $headers = array('Accept: application/xml', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST'); $response = ApiRestTestHelper::createXmlApiCall($this->serverUrl . '/test.php/accounts/account/api/read/1', 'GET', $headers); $response = XML2Array::createArray($response); $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']); $this->assertEquals('Sign in required.', $response['message']); }
/** * 转换响应 * @param $response * @return array * @throws Exception */ public static function parse_response($response, $format = "array") { //如果启用响应结果转换,则进行转换,否则原样返回 $body = $response->body; $headers = $response->header; switch (strtolower($format)) { case 'array': $body = empty($body) ? $body : XML2Array::createArray($body); break; case "json": $body = empty($body) ? $body : json_encode(XML2Array::createArray($body)); break; default: break; } return array('success' => $response->isOk(), 'status' => $response->status, 'header' => $headers, 'body' => $body); return $response; }
/** * Description: * Calculates checksum of file from /v1/post/... file. * Attribute meta required!!! * * @return MD5 checksum from all bookmarks hashes */ private function calculateChecksum($data) { $arr = XML2Array::createArray($data); $checksumTXT = ''; foreach ($arr['posts']['post'] as $post) { $checksumTXT .= $post["@attributes"]["meta"]; } return md5($checksumTXT); }
/** * Return the response represented as string * @return array */ public function convertResponseToArray() { if ($this->getResponse()) { $this->setArrayResponse(XML2Array::createArray($this->getResponse())); } return $this->getArrayResponse(); }
} } /*$xml = simplexml_load_file($xmlDestino, 'SimpleXMLElement',LIBXML_NOCDATA); $json = json_encode($xml); $XMLarray = json_decode($json,TRUE); krumo($XMLarray);*/ $xml = @file_get_contents($xmlDestino); if (!$xml) { $message = "NO existe {$xmlDestino} --> <a href='{$prevPaso}'>Crear</a>"; } else { // por lo visto es mejor iconv si el texto puede contener caracteres como € que no estan en utf_decode //$xml=iconv("UTF-8", "ISO-8859-1//TRANSLIT", $xml); // utf8_decode para los caracteres especiales, ñ y demás $xml = utf8_decode($xml); // cargamos el XML Televisions y lo transformamos en un Array para poder crear el formulario $TelevisionsArray = XML2Array::createArray($xml); $formulario = buildTelevisionsForm($TelevisionsArray); } //krumo($TelevisionsArray); // http://cruzroja.vivocomtech.net/Televisions.xml // construir formulario function buildTelevisionsForm($xmlArray) { //krumo($xmlArray); $baseNode = $xmlArray['Televisions']['Television']; //krumo(count($baseNode)); $form = new PhpFormBuilder(); $form->set_att('enctype', 'multipart/form-data'); $form->set_att('method', 'post'); $form->set_att('id', 'cr_xml_edit'); $count = 1;