• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP json_last_error_msg函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中json_last_error_msg函数的典型用法代码示例。如果您正苦于以下问题:PHP json_last_error_msg函数的具体用法?PHP json_last_error_msg怎么用?PHP json_last_error_msg使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了json_last_error_msg函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: 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


示例2: actionRun

 public function actionRun()
 {
     $queueName = Yii::$app->apnsGcm->queueName;
     $amqp = Yii::$app->amqp;
     $channel = $amqp->getChannel();
     $channel->queue_declare($queueName, false, true, false, false);
     $message = $channel->basic_get($queueName);
     if (empty($message) || !isset($message->body)) {
         return Controller::EXIT_CODE_NORMAL;
     }
     $body = json_decode($message->body);
     if (!$body) {
         $channel->basic_ack($message->delivery_info['delivery_tag']);
         Yii::error('Has no body. json: ' . json_last_error_msg(), 'ApnsGcm');
         return Controller::EXIT_CODE_ERROR;
     }
     // Log data
     Yii::info($message->body, 'ApnsGcm');
     /* @var $apnsGcm \bryglen\apnsgcm\ApnsGcm */
     Yii::$app->apnsGcm->sendMulti($body->type, (array) $body->tokens, $body->text, $body->payloadData, $body->args);
     if (!Yii::$app->apnsGcm->success) {
         Yii::error('Error send push: ' . var_export(Yii::$app->apnsGcm->error, true), 'ApnsGcm');
         return Controller::EXIT_CODE_ERROR;
     }
     $channel->basic_ack($message->delivery_info['delivery_tag']);
     $channel->close();
     return Controller::EXIT_CODE_NORMAL;
 }
开发者ID:gbksoft,项目名称:yii2-apnsgcm-through-rabbitmq,代码行数:28,代码来源:ApnsGcmController.php


示例3: __construct

 public function __construct($configFile, $env = '@')
 {
     $this->config = new \stdClass();
     if (!file_exists($configFile)) {
         throw new ConfigException('Configruation file not found: ' . $configFile);
     }
     $config = json_decode(file_get_contents($configFile));
     if ($config === null) {
         $msg = 'Configruation file failed to parse: ' . $configFile . ', with error: ' . json_last_error_msg();
         throw new ConfigException($msg);
     }
     if (!isset($config->{'@'})) {
         throw new ConfigException('Missing "@" section in parsed config: ' . $configFile);
     }
     // If modules is defined, copy to own variable
     if (isset($config->__modules__)) {
         $this->modules = $config->__modules__;
     }
     // Att default values to config
     $this->addValue('tmpConfig', $config->{'@'}, $this);
     if (isset($config->{$env})) {
         $config = [$env => $config->{$env}];
     }
     foreach ($config as $key => $value) {
         if (fnmatch($key, $env)) {
             $this->addValue('tmpConfig', $value, $this);
         }
     }
     $this->loadConfigModules();
     $this->addValue('config', $this->tmpConfig, $this);
     unset($this->tmpConfig);
 }
开发者ID:etu,项目名称:php-tools,代码行数:32,代码来源:JsonConfig.php


示例4: loadLanguagePackFrom

 /**
  * Load language pack resources from the given directory.
  *
  * @param string $directory
  */
 public function loadLanguagePackFrom($directory)
 {
     $name = $title = basename($directory);
     if (file_exists($manifest = $directory . '/composer.json')) {
         $json = json_decode(file_get_contents($manifest), true);
         if (empty($json)) {
             throw new RuntimeException("Error parsing composer.json in {$name}: " . json_last_error_msg());
         }
         $locale = array_get($json, 'extra.flarum-locale.code');
         $title = array_get($json, 'extra.flarum-locale.title', $title);
     }
     if (!isset($locale)) {
         throw new RuntimeException("Language pack {$name} must define \"extra.flarum-locale.code\" in composer.json.");
     }
     $this->locales->addLocale($locale, $title);
     if (!is_dir($localeDir = $directory . '/locale')) {
         throw new RuntimeException("Language pack {$name} must have a \"locale\" subdirectory.");
     }
     if (file_exists($file = $localeDir . '/config.js')) {
         $this->locales->addJsFile($locale, $file);
     }
     if (file_exists($file = $localeDir . '/config.css')) {
         $this->locales->addCssFile($locale, $file);
     }
     foreach (new DirectoryIterator($localeDir) as $file) {
         if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
             $this->locales->addTranslations($locale, $file->getPathname());
         }
     }
 }
开发者ID:flarum,项目名称:core,代码行数:35,代码来源:ConfigureLocales.php


示例5: getCurrentRemoteVersion

 /**
  * Retrieve the current version available remotely.
  *
  * @param Updater $updater
  * @return string|bool
  */
 public function getCurrentRemoteVersion(Updater $updater)
 {
     /** Switch remote request errors to HttpRequestExceptions */
     set_error_handler(array($updater, 'throwHttpRequestException'));
     $packageUrl = $this->getApiUrl();
     $package = json_decode(humbug_get_contents($packageUrl), true);
     restore_error_handler();
     if (null === $package || json_last_error() !== JSON_ERROR_NONE) {
         throw new JsonParsingException('Error parsing JSON package data' . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : ''));
     }
     $versions = array_keys($package['package']['versions']);
     $versionParser = new VersionParser($versions);
     if ($this->getStability() === self::STABLE) {
         $this->remoteVersion = $versionParser->getMostRecentStable();
     } elseif ($this->getStability() === self::UNSTABLE) {
         $this->remoteVersion = $versionParser->getMostRecentUnstable();
     } else {
         $this->remoteVersion = $versionParser->getMostRecentAll();
     }
     /**
      * Setup remote URL if there's an actual version to download
      */
     if (!empty($this->remoteVersion)) {
         $this->remoteUrl = $this->getDownloadUrl($package);
     }
     return $this->remoteVersion;
 }
开发者ID:twhiston,项目名称:tg,代码行数:33,代码来源:BitBucketStrategy.php


示例6: postJson

 public function postJson($url, array $data = [], array $headers = [], $decode_flags = 0)
 {
     $curlHeaders = [];
     if (!isset($headers['content-type'])) {
         $headers['content-type'] = 'application/json';
     }
     foreach ($headers as $k => $v) {
         $curlHeaders[] = $k . ': ' . $v;
     }
     $ch = $this->getHandle($url, [CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => $curlHeaders]);
     $res = curl_exec($ch);
     if (!$res) {
         throw new \RuntimeException('Empty response; ' . json_encode(curl_getinfo($ch)));
     }
     // discard sets of headers prior to the final one...and make sure the body doesn't
     // include stray headers (e.g. if running through a proxy that emits an initial 200
     // on-connect)
     $body = $res;
     do {
         list($rawHeaders, $body) = explode("\r\n\r\n", $body, 2);
     } while (strpos($body, 'HTTP/') === 0 && strpos($body, "\r\n\r\n") !== false);
     $resHeaders = [];
     foreach (array_slice(explode("\r\n", $rawHeaders), 1) as $rawHeader) {
         list($key, $value) = explode(': ', $rawHeader, 2);
         $resHeaders[$key] = $value;
     }
     $decoded = json_decode($body, $decode_flags);
     if ($decoded === false || $decoded === null) {
         throw new \RuntimeException('JSON decoding error: ' . json_last_error_msg());
     }
     return new HttpResponse($decoded, $resHeaders, curl_getinfo($ch, CURLINFO_HTTP_CODE));
 }
开发者ID:iansltx,项目名称:gcm-client,代码行数:32,代码来源:CurlClient.php


示例7: __construct

 public function __construct($jsonString, $check = true)
 {
     if ($check && false !== @json_decode($jsonString) && (bool) json_last_error()) {
         throw new \InvalidArgumentException(sprintf("Invalid JSON provided: %s", json_last_error_msg()));
     }
     $this->jsonString = $jsonString;
 }
开发者ID:borisguery,项目名称:json-builder,代码行数:7,代码来源:JsonLiteral.php


示例8: submit

 public function submit()
 {
     check_ajax_referer('ninja_forms_display_nonce', 'security');
     register_shutdown_function(array($this, 'shutdown'));
     if (!$this->_form_data) {
         if (function_exists('json_last_error') && function_exists('json_last_error_msg') && json_last_error()) {
             $this->_errors[] = json_last_error_msg();
         } else {
             $this->_errors[] = __('An unexpected error occurred.', 'ninja-forms');
         }
         $this->_respond();
     }
     $this->_form_id = $this->_data['form_id'] = $this->_form_data['id'];
     if (isset($this->_form_data['settings']['is_preview']) && $this->_form_data['settings']['is_preview']) {
         $this->_preview_data = get_user_option('nf_form_preview_' . $this->_form_id);
         // Add preview field keys to form data.
         foreach ($this->_form_data['fields'] as $key => $field) {
             $field_id = $field['id'];
             $this->_form_data['fields'][$key]['key'] = $this->_preview_data['fields'][$field_id]['settings']['key'];
         }
         if (!$this->_preview_data) {
             $this->_errors['preview'] = __('Preview does not exist.', 'ninja-forms');
             $this->_respond();
         }
     }
     $this->_data['settings'] = $this->_form_data['settings'];
     $this->_data['extra'] = $this->_form_data['extra'];
     $this->_data['fields'] = $this->_form_data['fields'];
     $this->_data = apply_filters('ninja_forms_submit_data', $this->_data);
     $this->validate_fields();
     $this->process_fields();
     $this->process();
 }
开发者ID:JSreactor,项目名称:MarketCrater.com,代码行数:33,代码来源:Submission.php


示例9: parseCommand

 /**
  * Parses the command from string
  *
  * @param string $commandString Raw command string
  *
  * @return Command
  * @throws ProtocolException If parsing fails
  */
 public function parseCommand($commandString)
 {
     $data = json_decode($commandString, true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         throw new ProtocolException('Json decode fail: ' . json_last_error_msg());
     }
     if (!is_array($data)) {
         throw new ProtocolException('Command data is not an array');
     }
     if (!isset($data['type']) || !$data['type']) {
         throw new ProtocolException('Command type not given');
     }
     $class = 'Bttw\\Infrastructure\\Command\\' . $data['type'];
     if (!class_exists($class)) {
         throw new ProtocolException('Command class does not exist');
     }
     switch ($class) {
         case GetBaskets::class:
             return new GetBaskets();
         case GetSolution::class:
             return new GetSolution();
         case PutBall::class:
             if (!isset($data['ballNumber'])) {
                 throw new ProtocolException('Ball number not given');
             }
             return new PutBall($data['ballNumber']);
         default:
             throw new ProtocolException('Unknown command type given');
     }
 }
开发者ID:sp-niemand,项目名称:balls-to-the-wall,代码行数:38,代码来源:JsonProtocol.php


示例10: loadJsonFile

 /**
  * @param string $file
  * @param bool $assoc
  * @param int $depth
  * @param int $options
  *
  * @throws RuntimeException
  * @throws LogicException
  *
  * @return mixed
  */
 protected function loadJsonFile($file, $assoc = false, $depth = 512, $options = 0)
 {
     $base_error = 'Can\'t find load JSON in file: ' . $file . ', ';
     if (!file_exists($file)) {
         throw new LogicException($base_error . 'does not exist.');
     }
     $file_content = file_get_contents($file);
     /**
      * Support iso to UTF-8
      */
     if (!mb_detect_encoding($file_content, 'UTF-8', true)) {
         $file_content = mb_convert_encoding($file_content, 'UTF-8', mb_detect_encoding($file_content, 'auto'));
         if (!mb_detect_encoding($file_content, 'UTF-8', true)) {
             throw new \RuntimeException($base_error . ' is not UTF-8 compatible or can not be converted to UTF-8.');
         }
     }
     /**
      * support for different parameters.
      */
     if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
         $data = json_decode($file_content, $assoc, $depth, $options);
     } elseif (version_compare(PHP_VERSION, '5.3.0') >= 0) {
         $data = json_decode($file_content, $assoc, $depth);
     } else {
         $data = json_decode($file_content, $assoc);
     }
     if (json_last_error()) {
         throw new RuntimeException($base_error . 'json error:' . json_last_error_msg(), json_last_error());
     }
     return $data;
 }
开发者ID:rubenvincenten,项目名称:bower-finder,代码行数:42,代码来源:BowerFinder.php


示例11: data

 function data()
 {
     // Sanitize the GET variables here.
     $cfg = array('columns' => array(), 'order' => array(), 'start' => 0, 'length' => -1, 'draw' => 0, 'search' => '', 'where' => '', 'mrColNotEmpty' => '');
     //echo '<pre>';print_r($_GET);return;
     $searchcols = array();
     // Process $_POST array
     foreach ($_POST as $k => $v) {
         if ($k == 'search') {
             $cfg['search'] = $v['value'];
         } elseif (isset($cfg[$k])) {
             $cfg[$k] = $v;
         }
     }
     // endforeach
     // Add columns to config
     $cfg['search_cols'] = $searchcols;
     //echo '<pre>';print_r($cfg);
     try {
         // Get model
         $obj = new Tablequery($cfg);
         //echo '<pre>';print_r($obj->fetch($cfg));
         echo json_encode($obj->fetch($cfg));
         // If there is an encoding error, show it
         if (json_last_error() != JSON_ERROR_NONE) {
             echo json_last_error_msg();
             print_r($obj->fetch($cfg));
         }
     } catch (Exception $e) {
         echo json_encode(array('error' => $e->getMessage(), 'draw' => intval($cfg['draw'])));
     }
 }
开发者ID:hymmm,项目名称:munkireport-php,代码行数:32,代码来源:datatables.php


示例12: configureResponseHandler

 private function configureResponseHandler(HandlerStack $handlerStack)
 {
     $handlerStack->remove('wechatClient:response');
     $handlerStack->push(function (callable $handler) {
         return function (RequestInterface $request, array $options = []) use($handler) {
             return $handler($request, $options)->then(function (ResponseInterface $response) use($request) {
                 // Non-success page, so we won't attempt to parse.
                 if ($response->getStatusCode() >= 300) {
                     return $response;
                 }
                 // Check if the response should be JSON decoded
                 $parse = ['application/json', 'text/json', 'text/plain'];
                 if (preg_match('#' . implode('|', $parse) . '#', $response->getHeaderLine('Content-Type')) < 1) {
                     return $response;
                 }
                 // Begin parsing JSON body.
                 $body = (string) $response->getBody();
                 $json = json_decode($body);
                 if (json_last_error() !== JSON_ERROR_NONE) {
                     throw new BadResponseFormatException(json_last_error_msg(), json_last_error());
                 }
                 if (isset($json->errcode) && $json->errcode != 0) {
                     $message = isset($json->errmsg) ? $json->errmsg : '';
                     $code = $json->errcode;
                     throw new APIErrorException($message, $code, $request, $response);
                 }
                 return $response;
             });
         };
     }, 'wechatClient:response');
 }
开发者ID:garbetjie,项目名称:wechat,代码行数:31,代码来源:Client.php


示例13: query

 function query($path, $content = array(), $method = 'GET')
 {
     @ini_set('track_errors', 1);
     // @ - may be disabled
     $file = @file_get_contents($this->_url . ($this->_db != "" ? "{$this->_db}/" : "") . $path, false, stream_context_create(array('http' => array('method' => $method, 'content' => json_encode($content), 'ignore_errors' => 1))));
     if (!$file) {
         $this->error = $php_errormsg;
         return $file;
     }
     if (!preg_match('~^HTTP/[0-9.]+ 2~i', $http_response_header[0])) {
         $this->error = $file;
         return false;
     }
     $return = json_decode($file, true);
     if (!$return) {
         $this->errno = json_last_error();
         if (function_exists('json_last_error_msg')) {
             $this->error = json_last_error_msg();
         } else {
             $constants = get_defined_constants(true);
             foreach ($constants['json'] as $name => $value) {
                 if ($value == $this->errno && preg_match('~^JSON_ERROR_~', $name)) {
                     $this->error = $name;
                     break;
                 }
             }
         }
     }
     return $return;
 }
开发者ID:amit0773,项目名称:manaslake,代码行数:30,代码来源:elastic.inc.php


示例14: __construct

 /**
  * Create an exception based on error codes returned by json_last_error function
  *
  * @param int $error A JSON error constant, as returned by json_last_error()
  * @see http://www.php.net/manual/en/function.json-last-error.php
  */
 public function __construct($error)
 {
     $message = 'Error while parsing Json configuration file: ';
     if (!function_exists('json_last_error_msg')) {
         switch ($error) {
             case JSON_ERROR_DEPTH:
                 $message .= 'maximum stack depth exceeded';
                 break;
             case JSON_ERROR_STATE_MISMATCH:
                 $message .= 'underflow or the modes mismatch';
                 break;
             case JSON_ERROR_CTRL_CHAR:
                 $message .= 'unexpected control character found';
                 break;
             case JSON_ERROR_SYNTAX:
                 $message .= 'syntax error, malformed JSON';
                 break;
             case JSON_ERROR_UTF8:
                 $message .= 'malformed UTF-8 characters, possibly incorrectly encoded';
                 break;
             default:
                 $message .= 'unknown error';
                 break;
         }
     } else {
         $message .= json_last_error_msg();
     }
     parent::__construct($message);
 }
开发者ID:disider,项目名称:Propel2,代码行数:35,代码来源:JsonParseException.php


示例15: process

 /**
  * @param Request $request
  *
  * @throws ValidationException
  * @throws MalformedContentException
  */
 public function process(Request $request)
 {
     if (!$request->attributes->has(RequestMeta::ATTRIBUTE_URI)) {
         throw new \UnexpectedValueException("Missing document URI");
     }
     $description = $this->repository->get($request->attributes->get(RequestMeta::ATTRIBUTE_URI));
     $operation = $description->getPath($request->attributes->get(RequestMeta::ATTRIBUTE_PATH))->getOperation($request->getMethod());
     $body = null;
     if ($request->getContent()) {
         $body = json_decode($request->getContent());
         if (json_last_error() !== JSON_ERROR_NONE) {
             throw new MalformedContentException(json_last_error_msg());
         }
     }
     $result = $this->validator->validate($operation->getRequestSchema(), $coercedParams = $this->parametersAssembler->assemble($operation, $request->query->all(), $request->attributes->all(), $request->headers->all(), $body));
     foreach ($coercedParams as $attribute => $value) {
         /** @var ScalarSchema  $schema*/
         if (($schema = $operation->getParameter($attribute)->getSchema()) instanceof ScalarSchema) {
             if ($schema->isDateTime()) {
                 $value = $this->dateTimeSerializer->deserialize($value, $schema);
             }
         }
         $request->attributes->set($attribute, $value);
     }
     if ($this->hydrator && ($bodyParam = $description->getRequestBodyParameter($operation->getPath(), $operation->getMethod()))) {
         $body = $this->hydrator->hydrate($body, $bodyParam->getSchema());
         $request->attributes->set($bodyParam->getName(), $body);
     }
     $request->attributes->set(RequestMeta::ATTRIBUTE, new RequestMeta($description, $operation));
     if (!$result->isValid()) {
         throw new ValidationException($result->getErrorMessages());
     }
 }
开发者ID:kleijnweb,项目名称:swagger-bundle,代码行数:39,代码来源:RequestProcessor.php


示例16: sendRequest

 /**
  * Запрос к API
  *
  * @param array $params
  * @return mixed|string
  */
 protected function sendRequest($params = array())
 {
     try {
         $curl = curl_init($this->endpoint);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
         $response = curl_exec($curl);
         if ($response === false) {
             throw new \Exception(curl_errno($curl) . ': ' . curl_error($curl));
         }
         curl_close($curl);
         $result = json_decode($response);
         if (json_last_error()) {
             throw new \Exception(json_last_error() . ': ' . json_last_error_msg());
         }
         if ($result->code) {
             throw new \Exception($result->code . ': ' . $result->msg);
         }
         return $result;
     } catch (\Exception $e) {
         $this->error = true;
         return $e->getMessage();
     }
 }
开发者ID:webjeyros,项目名称:kma_biz,代码行数:31,代码来源:kma_biz.php


示例17: getRate

 /**
  * @inheritdoc
  * @throws Api_Exception_ParserError
  */
 public function getRate($targetIso, $sourceIso)
 {
     try {
         $url = $this->_getApiUrl($targetIso, $sourceIso);
         $data = json_decode(file_get_contents($url), true);
     } catch (\Exception $e) {
         $data = null;
     }
     if (!$data) {
         throw new Api_Exception_ParserError('No API request');
     }
     if (json_last_error()) {
         throw new Api_Exception_ParserError(json_last_error_msg());
     }
     if (!isset($data['query'])) {
         throw new Api_Exception_ParserError('Wrong APIs request: no body');
     }
     $data = $data['query'];
     if (!isset($data['results']) || empty($data['results']['rate'])) {
         return null;
     }
     $rate = $data['results']['rate'];
     if (!isset($rate['Rate'])) {
         throw new Api_Exception_ParserError('Wrong APIs request: wrong structure, no rate');
     }
     return (double) $rate['Rate'];
 }
开发者ID:lordmx,项目名称:currency_parser,代码行数:31,代码来源:Yahoo.php


示例18: execute

 protected function execute($uri, array $parameters)
 {
     $parameters['key'] = YANDEX_TRANSLATE_KEY;
     curl_setopt($this->handler, CURLOPT_URL, static::BASE_URL . $uri);
     curl_setopt($this->handler, CURLOPT_POST, true);
     curl_setopt($this->handler, CURLOPT_POSTFIELDS, http_build_query($parameters));
     $remoteResult = curl_exec($this->handler);
     if ($remoteResult === false) {
         throw new \Exception(curl_error($this->handler), curl_errno($this->handler));
     }
     $result = json_decode($remoteResult, true);
     if (!$result) {
         $errorMessage = self::MESSAGE_UNKNOWN_ERROR;
         if (version_compare(PHP_VERSION, '5.3', '>=')) {
             if (json_last_error() !== JSON_ERROR_NONE) {
                 if (version_compare(PHP_VERSION, '5.5', '>=')) {
                     $errorMessage = json_last_error_msg();
                 } else {
                     $errorMessage = self::MESSAGE_JSON_ERROR;
                 }
             }
         }
         throw new \Exception(sprintf('%s: %s', self::MESSAGE_INVALID_RESPONSE, $errorMessage));
     } elseif (isset($result['code']) && $result['code'] > 200) {
         throw new \Exception($result['message'], $result['code']);
     }
     return $result;
 }
开发者ID:squaredcircle,项目名称:GroupBot,代码行数:28,代码来源:Translate.php


示例19: respondError

 public function respondError($msg, $code = 500)
 {
     switch ($code) {
         case 400:
             header("HTTP/1.0 400 Bad Request");
             break;
             break;
         case 401:
             header("HTTP/1.0 401 Unauthorized");
             break;
             break;
         default:
         case 500:
             header("HTTP/1.0 500 Internal Server Error.");
             break;
     }
     $json = json_encode(array("error" => true, "error_code" => $code, "error_msg" => $msg));
     if ($json === false) {
         header("HTTP/1.0 500 Internal Server Error.");
         $msg = 'JSON encoding error ' . json_last_error() . ': ' . json_last_error_msg();
         echo json_encode(array("error" => true, "error_code" => 500, "error_msg" => $msg));
         exit;
     }
     echo $json;
     exit;
 }
开发者ID:jimgitsit,项目名称:php-gozer,代码行数:26,代码来源:CoreAPIResponseJSON.php


示例20: run

 public function run()
 {
     $reqId = (int) $this->httpRequest->postData('id');
     $reqsData = json_decode($this->httpRequest->postData('data'), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         //Try with stripslashes()
         $reqsData = json_decode(stripslashes($this->httpRequest->postData('data')), true);
         if (json_last_error() !== JSON_ERROR_NONE) {
             $errMsg = '#' . json_last_error();
             if (function_exists('json_last_error_msg')) {
                 $errMsg .= ' ' . json_last_error_msg();
             }
             throw new \RuntimeException('Malformed JSON-encoded request (' . $errMsg . ')', 400);
         }
     }
     $responses = array();
     foreach ($reqsData as $requestData) {
         $apiCall = new Api();
         $apiCall->emulate($requestData, $this->httpRequest);
         $apiCall->run();
         $responses[] = $apiCall->httpResponse()->content();
     }
     $resp = new ApiGroupResponse();
     $resp->setResponses($responses);
     $resp->setId($reqId);
     $this->httpResponse->addHeader('Content-Type: application/json');
     if ($resp->cacheable()) {
         $this->httpResponse->setCacheable();
     }
     $this->httpResponse->setContent($resp);
 }
开发者ID:Rudi9719,项目名称:stein-syn,代码行数:31,代码来源:ApiGroup.class.php



注:本文中的json_last_error_msg函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP json_output函数代码示例发布时间:2022-05-15
下一篇:
PHP json_last_error函数代码示例发布时间:2022-05-15
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap