當前位置: 首頁>>代碼示例>>PHP>>正文


PHP json_encode函數代碼示例

本文整理匯總了PHP中json_encode函數的典型用法代碼示例。如果您正苦於以下問題:PHP json_encode函數的具體用法?PHP json_encode怎麽用?PHP json_encode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了json_encode函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: get

 public function get($limit = 1024)
 {
     header('Content-Type: application/json');
     $dates = json_decode(file_get_contents('hoa://Application/Database/Dates.json'), true);
     echo json_encode(array_slice($dates, 0, $limit));
     return;
 }
開發者ID:Hywan,項目名稱:Amine_and_Hamza,代碼行數:7,代碼來源:Dates.php

示例2: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!file_exists($path)) {
         $output->writeln("{$path} is not a file or a path");
     }
     $filePaths = [];
     if (is_file($path)) {
         $filePaths = [realpath($path)];
     } elseif (is_dir($path)) {
         $filePaths = array_diff(scandir($path), array('..', '.'));
     } else {
         $output->writeln("{$path} is not known.");
     }
     $generator = new StopwordGenerator($filePaths);
     if ($input->getArgument('type') === 'json') {
         echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
         echo json_last_error_msg();
         die;
         $output->write(json_encode($this->toArray($generator->getStopwords())));
     } else {
         $stopwords = $generator->getStopwords();
         $stdout = fopen('php://stdout', 'w');
         echo 'token,freq' . PHP_EOL;
         foreach ($stopwords as $token => $freq) {
             fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
         }
         fclose($stdout);
     }
 }
開發者ID:yooper,項目名稱:php-text-analysis,代碼行數:30,代碼來源:StopWordsCommand.php

示例3: setup_wizard

 /**
  * Show the setup wizard
  */
 public function setup_wizard()
 {
     if (empty($_GET['page']) || 'wc-setup' !== $_GET['page']) {
         return;
     }
     $this->steps = array('introduction' => array('name' => __('Introduction', 'woocommerce'), 'view' => array($this, 'wc_setup_introduction'), 'handler' => ''), 'pages' => array('name' => __('Page Setup', 'woocommerce'), 'view' => array($this, 'wc_setup_pages'), 'handler' => array($this, 'wc_setup_pages_save')), 'locale' => array('name' => __('Store Locale', 'woocommerce'), 'view' => array($this, 'wc_setup_locale'), 'handler' => array($this, 'wc_setup_locale_save')), 'shipping_taxes' => array('name' => __('Shipping & Tax', 'woocommerce'), 'view' => array($this, 'wc_setup_shipping_taxes'), 'handler' => array($this, 'wc_setup_shipping_taxes_save')), 'payments' => array('name' => __('Payments', 'woocommerce'), 'view' => array($this, 'wc_setup_payments'), 'handler' => array($this, 'wc_setup_payments_save')), 'next_steps' => array('name' => __('Ready!', 'woocommerce'), 'view' => array($this, 'wc_setup_ready'), 'handler' => ''));
     $this->step = isset($_GET['step']) ? sanitize_key($_GET['step']) : current(array_keys($this->steps));
     $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
     wp_register_script('select2', WC()->plugin_url() . '/assets/js/select2/select2' . $suffix . '.js', array('jquery'), '3.5.2');
     wp_register_script('wc-enhanced-select', WC()->plugin_url() . '/assets/js/admin/wc-enhanced-select' . $suffix . '.js', array('jquery', 'select2'), WC_VERSION);
     wp_localize_script('wc-enhanced-select', 'wc_enhanced_select_params', array('i18n_matches_1' => _x('One result is available, press enter to select it.', 'enhanced select', 'woocommerce'), 'i18n_matches_n' => _x('%qty% results are available, use up and down arrow keys to navigate.', 'enhanced select', 'woocommerce'), 'i18n_no_matches' => _x('No matches found', 'enhanced select', 'woocommerce'), 'i18n_ajax_error' => _x('Loading failed', 'enhanced select', 'woocommerce'), 'i18n_input_too_short_1' => _x('Please enter 1 or more characters', 'enhanced select', 'woocommerce'), 'i18n_input_too_short_n' => _x('Please enter %qty% or more characters', 'enhanced select', 'woocommerce'), 'i18n_input_too_long_1' => _x('Please delete 1 character', 'enhanced select', 'woocommerce'), 'i18n_input_too_long_n' => _x('Please delete %qty% characters', 'enhanced select', 'woocommerce'), 'i18n_selection_too_long_1' => _x('You can only select 1 item', 'enhanced select', 'woocommerce'), 'i18n_selection_too_long_n' => _x('You can only select %qty% items', 'enhanced select', 'woocommerce'), 'i18n_load_more' => _x('Loading more results…', 'enhanced select', 'woocommerce'), 'i18n_searching' => _x('Searching…', 'enhanced select', 'woocommerce'), 'ajax_url' => admin_url('admin-ajax.php'), 'search_products_nonce' => wp_create_nonce('search-products'), 'search_customers_nonce' => wp_create_nonce('search-customers')));
     wp_enqueue_style('woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array(), WC_VERSION);
     wp_enqueue_style('wc-setup', WC()->plugin_url() . '/assets/css/wc-setup.css', array('dashicons', 'install'), WC_VERSION);
     wp_register_script('wc-setup', WC()->plugin_url() . '/assets/js/admin/wc-setup.min.js', array('jquery', 'wc-enhanced-select'), WC_VERSION);
     wp_localize_script('wc-setup', 'wc_setup_params', array('locale_info' => json_encode(include WC()->plugin_path() . '/i18n/locale-info.php')));
     if (!empty($_POST['save_step']) && isset($this->steps[$this->step]['handler'])) {
         call_user_func($this->steps[$this->step]['handler']);
     }
     ob_start();
     $this->setup_wizard_header();
     $this->setup_wizard_steps();
     $this->setup_wizard_content();
     $this->setup_wizard_footer();
     exit;
 }
開發者ID:zengskie,項目名稱:Heroku-WordPress-PostgreSQL,代碼行數:28,代碼來源:class-wc-admin-setup-wizard.php

示例4: search_ac_init

function search_ac_init(&$a)
{
    if (!local_channel()) {
        killme();
    }
    $start = x($_REQUEST, 'start') ? $_REQUEST['start'] : 0;
    $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 100;
    $search = x($_REQUEST, 'search') ? $_REQUEST['search'] : "";
    if (x($_REQUEST, 'query') && strlen($_REQUEST['query'])) {
        $search = $_REQUEST['query'];
    }
    // Priority to people searches
    if ($search) {
        $people_sql_extra = protect_sprintf(" AND `xchan_name` LIKE '%" . dbesc($search) . "%' ");
        $tag_sql_extra = protect_sprintf(" AND term LIKE '%" . dbesc($search) . "%' ");
    }
    $r = q("SELECT `abook_id`, `xchan_name`, `xchan_photo_s`, `xchan_url`, `xchan_addr` FROM `abook` left join xchan on abook_xchan = xchan_hash WHERE abook_channel = %d \n\t\t{$people_sql_extra}\n\t\tORDER BY `xchan_name` ASC ", intval(local_channel()));
    $results = array();
    if ($r) {
        foreach ($r as $g) {
            $results[] = array("photo" => $g['xchan_photo_s'], "name" => '@' . $g['xchan_name'], "id" => $g['abook_id'], "link" => $g['xchan_url'], "label" => '', "nick" => '');
        }
    }
    $r = q("select distinct term, tid, url from term where type in ( %d, %d ) {$tag_sql_extra} group by term order by term asc", intval(TERM_HASHTAG), intval(TERM_COMMUNITYTAG));
    if (count($r)) {
        foreach ($r as $g) {
            $results[] = array("photo" => $a->get_baseurl() . '/images/hashtag.png', "name" => '#' . $g['term'], "id" => $g['tid'], "link" => $g['url'], "label" => '', "nick" => '');
        }
    }
    header("content-type: application/json");
    $o = array('start' => $start, 'count' => $count, 'items' => $results);
    echo json_encode($o);
    logger('search_ac: ' . print_r($x, true));
    killme();
}
開發者ID:TamirAl,項目名稱:hubzilla,代碼行數:35,代碼來源:search_ac.php

示例5: sendPushNotificationToGCM

function sendPushNotificationToGCM($registration_ids, $message)
{
    $GCM_SERVER_API_KEY = $_ENV["GCM_SERVER_API_KEY"];
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array('registration_ids' => $registration_ids, 'data' => $message);
    // Update your Google Cloud Messaging API Key
    if (!defined('GOOGLE_API_KEY')) {
        define("GOOGLE_API_KEY", $GCM_SERVER_API_KEY);
    }
    $headers = array('Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
開發者ID:kousiksatish,項目名稱:simple-gcm,代碼行數:25,代碼來源:internalgcmaccess.php

示例6: oembed

 /**
  * @param string $url
  * @return array
  */
 public function oembed($url)
 {
     $embedly = new Embedly();
     $response = $embedly->oembed(['url' => $url]);
     $data = json_decode(json_encode(reset($response)), true);
     return $data;
 }
開發者ID:ttreeagency,項目名稱:Embedly,代碼行數:11,代碼來源:EmbedlyHelper.php

示例7: http2_request

 private function http2_request($method, $path, $params)
 {
     $url = $this->api . rtrim($path, '/') . '/';
     if (!strcmp($method, "POST")) {
         $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
         $req->setHeader('Content-type: application/json');
         if ($params) {
             $req->setBody(json_encode($params));
         }
     } else {
         if (!strcmp($method, "GET")) {
             $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
             $url = $req->getUrl();
             $url->setQueryVariables($params);
         } else {
             if (!strcmp($method, "DELETE")) {
                 $req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
                 $url = $req->getUrl();
                 $url->setQueryVariables($params);
             }
         }
     }
     $req->setAdapter('curl');
     $req->setConfig(array('timeout' => 30, 'ssl_verify_peer' => FALSE));
     $req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
     $req->setHeader(array('Connection' => 'close', 'User-Agent' => 'PHPPlivo'));
     $r = $req->send();
     $status = $r->getStatus();
     $body = $r->getbody();
     $response = json_decode($body, true);
     return array("status" => $status, "response" => $response);
 }
開發者ID:popas,項目名稱:plivo,代碼行數:32,代碼來源:plivo.php

示例8: buildJavascriptConfiguration

 /**
  * Return JS configuration of the htmlArea plugins registered by the extension
  *
  * @return string JS configuration for registered plugins
  */
 public function buildJavascriptConfiguration()
 {
     $schema = array('types' => array(), 'properties' => array());
     // Parse configured schemas
     if (is_array($this->configuration['thisConfig']['schema.']) && is_array($this->configuration['thisConfig']['schema.']['sources.'])) {
         foreach ($this->configuration['thisConfig']['schema.']['sources.'] as $source) {
             $fileName = trim($source);
             $absolutePath = GeneralUtility::getFileAbsFileName($fileName);
             // Fallback to default schema file if configured file does not exists or is of zero size
             if (!$fileName || !file_exists($absolutePath) || !filesize($absolutePath)) {
                 $fileName = 'EXT:' . $this->extensionKey . '/Resources/Public/Rdf/MicrodataSchema/SchemaOrgAll.rdf';
             }
             $fileName = $this->getFullFileName($fileName);
             $rdf = file_get_contents($fileName);
             if ($rdf) {
                 $this->parseSchema($rdf, $schema);
             }
         }
     }
     uasort($schema['types'], array($this, 'compareLabels'));
     uasort($schema['properties'], array($this, 'compareLabels'));
     // Insert no type and no property entries
     $languageService = $this->getLanguageService();
     $noSchema = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No type');
     $noProperty = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No property');
     array_unshift($schema['types'], array('name' => 'none', 'label' => $noSchema));
     array_unshift($schema['properties'], array('name' => 'none', 'label' => $noProperty));
     // Store json encoded array in temporary file
     return 'RTEarea[editornumber].schemaUrl = "' . $this->writeTemporaryFile('schema_' . $this->configuration['language'], 'js', json_encode($schema)) . '";';
 }
開發者ID:dachcom-digital,項目名稱:TYPO3.CMS,代碼行數:35,代碼來源:MicroDataSchema.php

示例9: callMethod

 function callMethod()
 {
     $resultMethod = $this->createJSON();
     $apiName = stripcslashes($this->apiFunctionName[0]) . 'Api';
     $status = ApiConstants::$STATUS;
     if (file_exists(SERVER_DIR . 'app/Controller/Api/method/' . $apiName . '.php')) {
         $apiClass = ApiCore::getApiEngineByName($apiName);
         $apiReflection = new ReflectionClass($apiName);
         try {
             $functionName = $this->apiFunctionName[1];
             $apiReflection->getMethod($functionName);
             $response = ApiConstants::$RESPONSE;
             $res = $apiClass->{$functionName}($this->apiFunctionParams);
             if ($res == null) {
                 $resultMethod->{$status} = ApiConstants::$ERROR_NOT_FOUND_RECORD;
             } else {
                 if ($res->err == ApiConstants::$ERROR_PARAMS) {
                     $resultMethod->{$status} = ApiConstants::$ERROR_PARAMS;
                     $resultMethod->params = json_encode($apiFunctionParams);
                 } else {
                     $resultMethod->{$response} = $res;
                     $resultMethod->{$status} = ApiConstants::$ERROR_NO;
                 }
             }
         } catch (Exception $ex) {
             $resultMethod->errStr = $ex->getMessage();
         }
     } else {
         $resultMethod->errStr = 'Not found method';
         $resultMethod->{$status} = ApiConstants::$ERROR_NOT_FOUND_METHOD;
         $resultMethod->params = $this->apiFunctionParams;
     }
     return json_encode($resultMethod, JSON_UNESCAPED_UNICODE);
 }
開發者ID:smilexx,項目名稱:quest.dev,代碼行數:34,代碼來源:apiCore.php

示例10: getRequestMessage

 protected function getRequestMessage()
 {
     Json::arrayRecursive($this->request, "urlencode", false);
     $tMessage = json_encode($this->request);
     $tMessage = urldecode($tMessage);
     return $tMessage;
 }
開發者ID:pqshawn,項目名稱:sparrowPHP,代碼行數:7,代碼來源:QuickIdentityVerifyRequest.php

示例11: getQuestionListAction

 /**
  *用戶ID方式登錄
  */
 public function getQuestionListAction()
 {
     //基礎元素,必須參與驗證
     $Config['Time'] = abs(intval($this->request->Time));
     $Config['ReturnType'] = $this->request->ReturnType ? $this->request->ReturnType : 2;
     //URL驗證碼
     $sign = trim($this->request->sign);
     //私鑰,以後要移開到數據庫存儲
     $p_sign = 'lm';
     $sign_to_check = Base_common::check_sign($Config, $p_sign);
     //不參與驗證的元素
     //驗證URL是否來自可信的發信方
     if ($sign_to_check == $sign) {
         //驗證時間戳,時差超過600秒即認為非法
         if (abs($Config['Time'] - time()) <= 600) {
             $QuestionList = $this->oSecurityAnswer->getAll();
             $result = array('return' => 1, 'QuestionList' => $QuestionList);
         } else {
             $result = array('return' => 0, 'comment' => "時間有誤");
         }
     } else {
         $result = array('return' => 0, 'comment' => "驗證失敗,請檢查URL");
     }
     if ($Config['ReturnType']) {
         echo json_encode($result);
     } else {
         //			$r = $result['return']."|".iconv('UTF-8','GBK',$result['comment']);;
         //			if($result['return']==1)
         //			{
         //				$r = $r."|".$result['LoginId']."|".$result['adult'];
         //			}
         //			echo $r;
     }
 }
開發者ID:032404cxd,項目名稱:prototype_main,代碼行數:37,代碼來源:SecurityAnswerController.php

示例12: data

 public function data()
 {
     $courses = LearnHub::all();
     $res = DB::table('LearnHub')->select('category')->groupBy('category')->get();
     $categories = json_encode($res);
     return json_encode([$courses, $res]);
 }
開發者ID:noddypandey,項目名稱:basicangular,代碼行數:7,代碼來源:LearnhubController.php

示例13: initContent

 protected function initContent()
 {
     $request = $this->getContext()->getRequest();
     $auth = $this->getContext()->getAuth();
     $this->setTitle("Job status");
     $this->setRobots("noindex,nofollow");
     $this->bodyScripts[] = swarmpath("js/job.js");
     $error = $this->getAction()->getError();
     $data = $this->getAction()->getData();
     $html = '';
     if ($error) {
         $html .= html_tag('div', array('class' => 'alert alert-error'), $error['info']);
     }
     if (!isset($data["info"])) {
         return $html;
     }
     $this->setSubTitle('#' . $data["info"]["id"]);
     $project = $data['info']['project'];
     $isOwner = $auth && $auth->project->id === $project['id'];
     $html .= '<h2>' . $data["info"]["nameHtml"] . '</h2>' . '<p><em>Submitted by ' . html_tag('a', array('href' => $project['viewUrl']), $project['display_title']) . ' ' . self::getPrettyDateHtml($data["info"], 'created') . '</em>.</p>';
     if ($isOwner) {
         $html .= '<script>SWARM.jobInfo = ' . json_encode($data["info"]) . ';</script>';
         $action_bar = '<div class="form-actions swarm-item-actions">' . ' <button class="swarm-reset-runs-failed btn btn-info">Reset failed runs</button>' . ' <button class="swarm-reset-runs btn btn-info">Reset all runs</button>' . ' <button class="swarm-delete-job btn btn-danger">Delete job</button>' . '</div>' . '<div class="swarm-wipejob-error alert alert-error" style="display: none;"></div>';
     } else {
         $action_bar = '';
     }
     $html .= $action_bar;
     $html .= '<table class="table table-bordered swarm-results swarm-results-unbound-auth"><thead>' . self::getUaHtmlHeader($data['userAgents']) . '</thead><tbody>' . self::getUaRunsHtmlRows($data['runs'], $data['userAgents'], $isOwner) . '</tbody></table>';
     $html .= $action_bar;
     return $html;
 }
開發者ID:TestArmada,項目名稱:admiral,代碼行數:31,代碼來源:JobPage.php

示例14: put

 public function put($url, $body = null)
 {
     curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'PUT');
     curl_setopt($this->_ch, CURLOPT_URL, $this->_base_uri . $url);
     curl_setopt($this->_ch, CURLOPT_POSTFIELDS, json_encode($body));
     return json_decode(curl_exec($this->_ch));
 }
開發者ID:KopjeKoffie,項目名稱:api-examples,代碼行數:7,代碼來源:liquidplanner.php

示例15: createDefaultGroup

 public function createDefaultGroup()
 {
     $defaultgroups = json_decode(MONITIS_ADMIN_CONTACT_GROUPS, true);
     $existedGroups = MonitisApi::getContactGroupList();
     // existed monitis groups
     foreach ($defaultgroups as $mType => $groupName) {
         $group = MonitisHelper::in_array($existedGroups, 'id', MonitisConf::$settings['groups'][$mType]['groupId']);
         $alerts = json_decode(MONITIS_NOTIFICATION_RULE, true);
         if ($mType == 'internal') {
             $alerts['minFailedLocationCount'] = null;
         }
         $groupId = $group['id'] ? $group['id'] : 0;
         $notifByTypeGroup = MonitisApiHelper::getNotificationRuleByType($mType, $groupId);
         $alertRulesDefault = $notifByTypeGroup ? $notifByTypeGroup : $alerts;
         if ($group) {
             MonitisConf::$settings['groups'][$mType]['groupId'] = $group['id'];
             MonitisConf::$settings['groups'][$mType]['groupName'] = $group['name'];
             MonitisConf::$settings['groups'][$mType]['alert'] = $alertRulesDefault;
         } else {
             $newGroupName = $groupName;
             $resp = MonitisApi::addContactGroup(1, $newGroupName);
             if ($resp['status'] == 'ok') {
                 MonitisConf::$settings['groups'][$mType]['groupId'] = $resp['data'];
                 MonitisConf::$settings['groups'][$mType]['groupName'] = $newGroupName;
                 MonitisConf::$settings['groups'][$mType]['alert'] = $alertRulesDefault;
             } else {
                 // error
                 return array('status' => 'error', 'msg' => 'Add contact group error ' . $resp['error']);
             }
         }
         // $r = $this->addContacts(ucfirst($mType), MonitisConf::$settings['groups'][$mType]['groupId']);
     }
     MonitisConf::update_settings(json_encode(MonitisConf::$settings));
     return array('status' => 'ok', 'msg' => 'External, internal groups sets success');
 }
開發者ID:carriercomm,項目名稱:WHMCS,代碼行數:35,代碼來源:notifications.class.php


注:本文中的json_encode函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。