本文整理汇总了PHP中json_last_error_msg函数的典型用法代码示例。如果您正苦于以下问题:PHP json_last_error_msg函数的具体用法?PHP json_last_error_msg怎么用?PHP json_last_error_msg使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_last_error_msg函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
}
示例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;
}
示例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);
}
示例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());
}
}
}
示例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;
}
示例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));
}
示例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;
}
示例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();
}
示例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');
}
}
示例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;
}
示例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'])));
}
}
示例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');
}
示例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;
}
示例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);
}
示例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());
}
}