本文整理汇总了PHP中json_last_error函数的典型用法代码示例。如果您正苦于以下问题:PHP json_last_error函数的具体用法?PHP json_last_error怎么用?PHP json_last_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_last_error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: make_request
/**
* Make API request.
*
* @access public
* @param string $path
* @param array $options
* @param bool $return_status (default: false)
* @param string $method (default: 'GET')
* @return void
*/
public function make_request($path, $options = array(), $method = 'GET', $return_key = null)
{
/* Build request URL. */
$request_url = 'https://' . $this->subdomain . '.campfirenow.com/' . $path . '.json';
/* Setup request arguments. */
$args = array('headers' => array('Accept' => 'application/json', 'Authorization' => 'Basic ' . base64_encode($this->api_token . ':x'), 'Content-Type' => 'application/json'), 'method' => $method, 'sslverify' => $this->verify_ssl);
/* Add request options to body of POST and PUT requests. */
if ($method == 'POST' || $method == 'PUT') {
$args['body'] = json_encode($options);
}
/* Execute request. */
$result = wp_remote_request($request_url, $args);
/* If WP_Error, throw exception */
if (is_wp_error($result)) {
throw new Exception('Request failed. ' . $result->get_error_messages());
}
/* Decode JSON. */
$decoded_result = json_decode($result['body'], true);
/* If invalid JSON, return original result body. */
if (json_last_error() !== JSON_ERROR_NONE) {
return trim($result['body']);
}
/* If return key is set and exists, return array item. */
if ($return_key && array_key_exists($return_key, $decoded_result)) {
return $decoded_result[$return_key];
}
return $decoded_result;
}
示例2: to_xml
/**
* Converts a JSON string to a CFSimpleXML object.
*
* @param string|array $json (Required) Pass either a valid JSON-formatted string, or an associative array.
* @param SimpleXMLElement $xml (Optional) An XML object to add nodes to. Must be an object that is an <code>instanceof</code> a <code>SimpleXMLElement</code> object. If an object is not passed, a new one will be generated using the classname defined for <code>$parser</code>.
* @param string $parser (Optional) The name of the class to use to parse the XML. This class should extend <code>SimpleXMLElement</code>. Has a default value of <code>CFSimpleXML</code>.
* @return CFSimpleXML An XML representation of the data.
*/
public static function to_xml($json, SimpleXMLElement $xml = null, $parser = 'CFSimpleXML')
{
// If there isn't an XML object, create one
if (!$xml) {
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><rootElement/>', $parser);
}
// If we haven't parsed the JSON, do it
if (!is_array($json)) {
$json = json_decode($json, true);
if (function_exists('json_last_error')) {
// Did we encounter an error?
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
throw new JSON_Exception('Maximum stack depth exceeded.');
case JSON_ERROR_CTRL_CHAR:
throw new JSON_Exception('Unexpected control character found.');
case JSON_ERROR_SYNTAX:
throw new JSON_Exception('Syntax error; Malformed JSON.');
case JSON_ERROR_STATE_MISMATCH:
throw new JSON_Exception('Invalid or malformed JSON.');
}
} else {
throw new JSON_Exception('Unknown JSON error. Be sure to validate your JSON and read the notes on http://php.net/json_decode.');
}
}
// Hand off for the recursive work
self::process_json($json, $xml, $parser);
return $xml;
}
示例3: decode
/**
* Decodes the given $encodedValue string which is
* encoded in the JSON format
*
* Uses ext/json's json_decode if available.
*
* @param string $encodedValue Encoded in JSON format
* @param int $objectDecodeType Optional; flag indicating how to decode
* objects. See {@link Zend_Json_Decoder::decode()} for details.
* @return mixed
*/
public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
{
$encodedValue = (string) $encodedValue;
if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
$decode = json_decode($encodedValue, $objectDecodeType);
// php < 5.3
if (!function_exists('json_last_error')) {
if ($decode === $encodedValue) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Decoding failed');
}
// php >= 5.3
} elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
require_once 'Zend/Json/Exception.php';
switch ($jsonLastErr) {
case JSON_ERROR_DEPTH:
throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
case JSON_ERROR_CTRL_CHAR:
throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
case JSON_ERROR_SYNTAX:
throw new Zend_Json_Exception('Decoding failed: Syntax error');
default:
throw new Zend_Json_Exception('Decoding failed');
}
}
return $decode;
}
require_once 'Zend/Json/Decoder.php';
return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
}
示例4: validateInput
/**
* Valida el formato de los datos de entrada.
* Verifica que el ContentType sea application/json y que el JSON de entrada
* esté bien formado.
*/
protected function validateInput()
{
$this->before(function ($request) {
if (strtolower($request->contentType) !== "application/json") {
throw new Exception("El ContentType debe ser application/json", Response::BADREQUEST);
}
try {
$request->data = json_decode($request->data, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
break;
case JSON_ERROR_SYNTAX:
throw new Exception("JSON mal formado", Response::BADREQUEST);
case JSON_ERROR_UTF8:
throw new Exception("La codificación de caracteres debe ser UTF-8", Response::BADREQUEST);
default:
throw new Exception("Error en el objeto de entrada.", Response::BADREQUEST);
}
if (empty($request->data)) {
throw new Exception("No hay datos para procesar", Response::BADREQUEST);
}
} catch (Exception $e) {
$response = json_encode($this->getErrorArray($e->getMessage(), $e->getCode()));
throw new Exception($response, $e->getCode());
}
});
}
示例5: _createExceptionFromLastError
/**
* Returns an exception describing the last JSON error
*
* @return Exception
*/
protected function _createExceptionFromLastError()
{
if (!function_exists('json_last_error_msg')) {
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$errorMessage = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$errorMessage = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$errorMessage = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$errorMessage = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$errorMessage = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$errorMessage = 'Unknown JSON error';
}
} else {
$errorMessage = json_last_error_msg();
}
return new Exception($errorMessage, json_last_error());
}
示例6: getResponsePayload
/**
* Return the response payload from the current response.
*
* @return mixed
*/
protected function getResponsePayload()
{
if (!$this->responsePayload) {
$json = json_decode($this->getResponse()->getBody(true));
if (json_last_error() !== JSON_ERROR_NONE) {
$message = 'Failed to decode JSON body ';
switch (json_last_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;
}
throw new \Exception($message);
}
$this->responsePayload = $json;
}
return $this->responsePayload;
}
示例7: received
/**
* Get all of the received requests as a RingPHP request structure.
*
* @return array
* @throws \RuntimeException
*/
public static function received()
{
if (!self::$started) {
return [];
}
$response = self::send('GET', '/guzzle-server/requests');
$body = Core::body($response);
$result = json_decode($body, true);
if ($result === false) {
throw new \RuntimeException('Error decoding response: ' . json_last_error());
}
foreach ($result as &$res) {
if (isset($res['uri'])) {
$res['resource'] = $res['uri'];
}
if (isset($res['query_string'])) {
$res['resource'] .= '?' . $res['query_string'];
}
if (!isset($res['resource'])) {
$res['resource'] = '';
}
// Ensure that headers are all arrays
if (isset($res['headers'])) {
foreach ($res['headers'] as &$h) {
$h = (array) $h;
}
unset($h);
}
}
unset($res);
return $result;
}
示例8: decode
public function decode($json)
{
$result = json_decode($json, true);
$error = '';
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$error = ' - The maximum stack depth has been exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = ' - Invalid or malformed JSON';
break;
case JSON_ERROR_CTRL_CHAR:
$error = ' - Control character error, possibly incorrectly encoded';
break;
case JSON_ERROR_SYNTAX:
$error = ' - Syntax error';
break;
case JSON_ERROR_UTF8:
$error = ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
}
if (!empty($error)) {
throw new Exception('JSON Error: ' . $error);
}
return $result;
}
示例9: encode
/**
* @param array $object
* @param boolean $allowBinary
* @return string
* @throws InvalidArgumentException
*/
protected function encode($object, $allowBinary = true)
{
$json = @json_encode($object);
if ($last = json_last_error()) {
switch ($last) {
case JSON_ERROR_NONE:
break;
case JSON_ERROR_DEPTH:
throw new InvalidArgumentException('Maximum stack depth exceeded');
case JSON_ERROR_STATE_MISMATCH:
throw new InvalidArgumentException('Underflow or the modes mismatch');
case JSON_ERROR_CTRL_CHAR:
throw new InvalidArgumentException('Unexpected control character found');
case JSON_ERROR_SYNTAX:
throw new InvalidArgumentException('Syntax error, malformed JSON');
case JSON_ERROR_UTF8:
if (!$allowBinary) {
throw new InvalidArgumentException('Invalid binary string in object to encode; JSON strings must be UTF-8');
}
$object = $this->encodeBinary($object);
$json = $this->encode($object, false);
break;
default:
throw new InvalidArgumentException('Unknown error in JSON encode');
}
}
return $json;
}
示例10: request
function request($http_method, array $data = array(), array $params = array(), array $option = array())
{
static $key_colon_value = null;
if (is_null($key_colon_value)) {
$key_colon_value = function ($k, $v) {
return is_int($k) ? $v : "{$k}: {$v}";
};
}
$opt = array_merge(array('space_name' => $this->space, 'header' => array()), $option);
$query = array_merge(array('apiKey' => $this->apiKey), $data);
$segments = array();
foreach ($this->api as $api) {
$segments[] = array_key_exists($api, $params) ? $params[$api] : $api;
}
$uri = implode('/', $segments);
$http_method = strtoupper($http_method);
switch ($http_method) {
case 'POST':
$content = http_build_query($query, '', '&');
$header = array_merge(array('Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => strlen($content)), $opt['header']);
$query = array('apiKey' => $this->apiKey);
break;
case 'GET':
$header = array_merge(array(), $opt['header']);
break;
default:
$header = array_merge(array(), $opt['header']);
}
if (!isset($url)) {
$url = sprintf(self::URL_TEMPLATE, $opt['space_name'], $uri, http_build_query($query, '', '&'));
}
$context = array('http' => array('method' => $http_method, 'header' => implode("\r\n", array_map($key_colon_value, array_keys($header), array_values($header))), 'ignore_errors' => true));
if (isset($content)) {
$context['http']['content'] = $content;
}
$response = file_get_contents($url, false, stream_context_create($context));
$type = $this->responseContexType($http_response_header);
switch ($type) {
case 'application/json':
$res = $json = json_decode($response, true);
$json_error = json_last_error();
break;
case 'application/octet-stream':
$res = $response;
break;
default:
$res = $response;
}
if (isset($json) and isset($json['errors'])) {
// error
throw new BacklogException($json['errors'][0]['message'], $json['errors'][0]['code'], null, $json);
} elseif ('application/json' == $type and JSON_ERROR_NONE !== $json_error and JSON_ERROR_SYNTAX !== $json_error) {
// error
throw new BacklogException('json error.', $json_error, null, $response);
} elseif (empty($response)) {
// error
throw new BacklogException('Not Found Content', 404);
}
return $res;
}
示例11: installAction
/**
* @param Request $request
* @param Application $app
*
* @return Response
*
* @throws \Exception
*/
public function installAction(Request $request, Application $app)
{
$installer = json_decode($request->getContent(), true);
$app['logger']->info('Install Callback');
if (json_last_error()) {
$app['logger']->error('Install JSON Error: ' . json_last_error_msg());
throw new \Exception('JSON Error');
}
$oauthId = $this->getInstallValue($installer, 'oauthId');
$oauthSecret = $this->getInstallValue($installer, 'oauthSecret');
$groupId = $this->getInstallValue($installer, 'groupId', true);
$roomId = $this->getInstallValue($installer, 'roomId', true);
if ($oauthId === null || $oauthSecret === null || $groupId === null) {
throw new \Exception('Invalid installation request');
}
$app['logger']->debug(sprintf('Got oauthId "%s" and oauthSecret "%s"', $oauthId, $oauthSecret));
/* @var Registry $registry */
$registry = $app['hc.api_registry'];
$registry->install($oauthId, $oauthSecret, $groupId, $roomId);
/** @var \Venyii\HipChatCommander\Api\Client $client */
$client = $app['hc.api_client']($oauthId);
try {
// fetch auth token
$authToken = $client->renewAuthToken($oauthId, $oauthSecret);
$app['logger']->debug(sprintf('Got authToken "%s"', $authToken));
} catch (\Exception $e) {
$registry->uninstall($oauthId);
throw $e;
}
return new Response(null, 200);
}
示例12: createRequest
public function createRequest()
{
$uri = $_SERVER['REQUEST_URI'];
$basePath = $this->configuration->getBasePath();
if ($basePath && strncmp($uri, $basePath, strlen($basePath)) !== 0) {
throw new ApiException("Invalid endpoint");
}
$uri = substr($uri, strlen($basePath) - 1);
if ($this->configuration->getPublicKey() !== trim($_SERVER['HTTP_X_API_KEY'])) {
throw new AuthorizationException("Invalid API key");
}
$hasBody = $this->hasBody();
$input = $hasBody ? file_get_contents('php://input') : '';
$signature = hash_hmac('sha256', $uri . $input, $this->configuration->getPrivateKey());
if ($signature !== trim($_SERVER['HTTP_X_API_SIGNATURE'])) {
throw new AuthorizationException("Invalid signature");
}
if ($hasBody) {
$parameters = json_decode($input, JSON_OBJECT_AS_ARRAY);
if ($parameters === NULL && $input !== '' && strcasecmp(trim($input, " \t\n\r"), 'null') !== 0) {
$error = json_last_error();
throw new ApiException('JSON parsing error: ' . $error);
}
} else {
$parameters = filter_input_array(INPUT_GET, FILTER_UNSAFE_RAW);
}
$name = ($a = strpos($uri, '?')) !== FALSE ? substr($uri, 0, $a) : $uri;
return new Request(ltrim($name, '/'), $_SERVER['REQUEST_METHOD'], $parameters);
}
示例13: parse_json
protected function parse_json($json_file)
{
if (is_file($json_file) and is_readable($json_file)) {
$data = file_get_contents($json_file);
} else {
throw new \Exception("The {$json_file} file could not be found or could not be read.");
}
$data = json_decode($data, true);
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$error = "The {$json_file} file exceeded maximum stack depth.";
break;
case JSON_ERROR_STATE_MISMATCH:
$error = "The {$json_file} file hit an underflow or the mods mismatched.";
break;
case JSON_ERROR_CTRL_CHAR:
$error = "The {$json_file} file has an unexpected control character.";
break;
case JSON_ERROR_SYNTAX:
$error = "The {$json_file} file has a syntax error, it\\'s JSON is malformed.";
break;
case JSON_ERROR_UTF8:
$error = "The {$json_file} file has malformed UTF-8 characters, it could be incorrectly encoded.";
break;
case JSON_ERROR_NONE:
default:
$error = '';
}
if (!empty($error)) {
throw new \Exception($error);
}
return $data;
}
示例14: __construct
/**
* Loads the request schema from a file.
*
* @param string $file The full path to the file containing the [WDVSS schema](https://github.com/alexweissman/wdvss).
* @throws Exception The file does not exist or is not a valid JSON schema.
*/
public function __construct($file)
{
$this->_schema = json_decode(file_get_contents($file), true);
if ($this->_schema === null) {
throw new \Exception("Either the schema '{$file}' could not be found, or it does not contain a valid JSON document: " . json_last_error());
}
}
示例15: read
/**
* Reads json file.
*
* @throws \RuntimeException
*
* @return mixed
*/
public function read()
{
$json = @file_get_contents($this->path);
if (false === $json) {
throw new \RuntimeException('Could not read ' . $this->path);
}
$arr = json_decode($json, true);
$error = null;
switch (json_last_error()) {
case JSON_ERROR_NONE:
break;
case JSON_ERROR_DEPTH:
$error = 'Maximum stack depth exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Underflow or the modes mismatch.';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Unexpected control character found.';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error, malformed JSON.';
break;
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
break;
default:
$error = 'Unknown error';
break;
}
if ($error) {
throw new \RuntimeException($error . ' Path: ' . $this->path);
}
return $arr;
}