Home Backend Development PHP Tutorial Two example methods for parsing json data in php_PHP tutorial

Two example methods for parsing json data in php_PHP tutorial

Jul 20, 2016 am 11:07 AM
json php web Example data method flow parse

Two example methods of php parsing json data

Most popular web services such as twitter provide data through open APIs. It can always know how to parse various transmission formats of API data, including JSON. , XML, etc.


$json_string='{"id":1,"name":"php100.com","email":"php tutorial">admin@php100.com","interest": ["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[ 1]; //prints php


ecshop parses json class

if (!defined('EC_CHARSET'))
{
define('EC_CHARSET', ' utf-8');
}

class JSON
{
var $at = 0;
var $ch = '';
var $text = '' ;

function encode($arg, $force = true)
{
static $_force;
if (is_null($_force))
{
$_force = $force;
}

if ($_force && EC_CHARSET == 'utf-8' && function_exists('json_encode'))
{
return json_encode($arg);
}

$returnValue = '';
$c = '';
$i = '';
$l = '';
$s = '';
$v = '';
$numeric = true;

switch (gettype($arg))
{
case 'array':
foreach ($arg AS $i => $v)
{
if (!is_numeric($i))
{
$numeric = false;
break;
}
}

if ($numeric)
{
foreach ($arg AS $i => $v)
{
if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode($arg[$i]);
}

$returnValue = '[' . $s . ']';
}
else
{
foreach ($arg AS $i => $v)
{
if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode($i) . ':' . $this->encode($arg[$i]);
}

$returnValue = '{' . $s . '}';
}
break;

case 'object':
foreach (get_object_vars($arg) AS $i => $v)
{
$v = $this->encode($v);

if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode( $i) . ':' . $v;
}

$returnValue = '{' . $s . '}';
break;

case 'integer' :
case 'double':
$returnValue = is_numeric($arg) ? (string) $arg : 'null';
break;

case 'string':
$returnValue = '"' . strtr($arg, array(
"r" => 'r', "n" => 'n', "t" => 't', "b" => 'b',
"f" => 'f', '' => '', '"' => '"',
"x00" => 'u0000' , "x01" => 'u0001', "x02" => 'u0002', "x03" => 'u0003',
"x04" => 'u0004', "x05" => 'u0005', "x06" => 'u0006', "x07" => 'u0007',
"x08" => 'b', "x0b" => 'u000b', "x0c" => 'f', "x0e" => 'u000e',
"x0f" => 'u000f', "x10" => 'u0010', "x11" => 'u0011', "x12" => 'u0012',
"x13" => 'u0013', "x14" => 'u0014', "x15" => 'u0015', "x16" => ' u0016',
"x17" => 'u0017', "x18" => 'u0018', "x19" => 'u0019', "x1a" => 'u001a',
" x1b" => 'u001b', "x1c" => 'u001c', "x1d" => 'u001d', "x1e" => 'u001e',
"x1f" => 'u001f '
)) . '"';
break;

case 'boolean':
$returnValue = $arg?'true':'false';
break;

default:
$returnValue = 'null';
}

return $returnValue;
}

function decode($text,$type= 0) // Default type=0 returns obj, type=1 returns array
{
if (empty($text))
{
return '';
}
elseif (!is_string($text))
{
return false;
}

if (EC_CHARSET === 'utf-8' && function_exists('json_decode'))
{
return $this->addslashes_deep_obj(json_decode(strips tutorial lashes($text),$type));
}

$this->at   = 0;
$this->ch   = '';
$this->text = strtr(stripslashes($text), array(
"r"   => '', "n"   => '', "t"   => '', "b"   => '',
"x00" => '', "x01" => '', "x02" => '', "x03" => '',
"x04" => '', "x05" => '', "x06" => '', "x07" => '',
"x08" => '', "x0b" => '', "x0c" => '', "x0e" => '',
"x0f" => '', "x10" => '', "x11" => '', "x12" => '',
"x13" => '', "x14" => '', "x15" => '', "x16" => '',
"x17" => '', "x18" => '', "x19" => '', "x1a" => '',
"x1b" => '', "x1c" => '', "x1d" => '', "x1e" => '',
"x1f" => ''
));

$this->next();
$return = $this->val();

$result = empty($type) ? $return : $this->object_to_array($return);

return addslashes_deep_obj($result);
}

/**
* triggers a PHP_ERROR
*
* @access   private
* @param    string    $m    error message
*
* @return   void
*/
function error($m)
{
trigger_error($m . ' at offset ' . $this->at . ': ' . $this->text, E_USER_ERROR);
}

/**
* returns the next character of a JSON string
*
* @access  private
*
* @return  string
*/
function next()
{
$this->ch = !isset($this->text{$this->at}) ? '' : $this->text{$this->at};
$this->at++;

return $this->ch;
}

/**
* handles strings
*
* @access  private
*
* @return  void
*/
function str()
{
$i = '';
$s = '';
$t = '';
$u = '';

if ($this->ch == '"')
{
while ($this->next() !== null)
{
if ($this->ch == '"')
{
$this->next();

return $s;
}
elseif ($this->ch == '')
{
switch ($this->next())
{
case 'b':
$s .= 'b';
break;

case 'f':
$s .= 'f';
break;

case 'n':
$s .= 'n';
break;

case 'r':
$s .= 'r';
break;

case 't':
$s .= 't';
break;

case 'u':
$u = 0;

for ($i = 0; $i < 4; $i++)
{
$t = (integer) sprintf('%01c', hexdec($this->next()));

if (!is_numeric($t))
{
break 2;
}
$u = $u * 16 + $t;
}

$s .= chr($u);
break;
case ''':
$s .= ''';
break;
default:
$s .= $this->ch;
}
}
else
{
$s .= $this->ch;
}
}
}

$this->error('Bad string');
}

/**
* handless arrays
*
* @access  private
*
* @return  void
*/
function arr()
{
$a = array();

if ($this->ch == '[')
{
$this->next();

if ($this->ch == ']')
{
$this->next();

return $a;
}

while (isset($this->ch))
{
array_push($a, $this->val());

if ($this->ch == ']')
{
$this->next();

return $a;

}
elseif ($this->ch != ',')
{
break;
}

$this->next();

}

$this->error('Bad array');
}
}

/**
* handles objects
*
* @access  public
*
* @return  void
*/
function obj()
{
$k = '';
$o = new StdClass();

if ($this->ch == '{')
{
$this->next();

if ($this->ch == '}')
{
$this->next();

return $o;
}

while ($this->ch)
{
$k = $this->str();

if ($this->ch != ':')
{
break;
}

$this->next();
$o->$k = $this->val();

if ($this->ch == '}')
{
$this->next();

return $o;
}
elseif ($this->ch != ',')
{
break;
}

$this->next();
}
}

$this->error('Bad object');
}

/**
* handles objects
*
* @access  public
*
* @return  void
*/
function assoc()
{
$k = '';
$a = array();

if ($this->ch == '<')
{
$this->next();

if ($this->ch == '>')
{
$this->next();

return $a;
}

while ($this->ch)
{
$k = $this->str();

if ($this->ch != ':')
{
break;
}

$this->next();
$a[$k] = $this->val();

if ($this->ch == '>')
{
$this->next();

return $a;
}
elseif ($this->ch != ',')
{
break;
}

$this->next();
}
}

$this->error('Bad associative array');
}

/**
* handles numbers
*
* @access  private
*
* @return  void
*/
function num()
{
$n = '';
$v = '';

if ($this->ch == '-')
{
$n = '-';
$this->next();
}

while ($this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
$this->next();
}

if ($this->ch == '.')
{
$n .= '.';

while ($this->next() && $this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
}
}

if ($this->ch == 'e' || $this->ch == 'E')
{
$n .= 'e';
$this->next();

if ($this->ch == '-' || $this->ch == '+')
{
$n .= $this->ch;
$this->next();
}

while ($this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
$this->next();
}
}

$v += $n;

if (!is_numeric($v))
{
$this->error('Bad number');
}
else
{
return $v;
}
}

/**
* handles words
*
* @access  private
*
* @return  mixed
*/
function word()
{
switch ($this->ch)
{
case 't':

if ($this->next() == 'r' && $this->next() == 'u' && $this->next() == 'e')
{
$this->next();

return true;
}
break;

case 'f':
if ($this->next() == 'a' && $this->next() == 'l' && $this->next() == 's' && $this->next() == 'e')
{
$this->next();

return false;
}
break;

case 'n':
if ($this->next() == 'u' && $this->next() == 'l' && $this->next() == 'l')
{
$this->next();

return null;
}
break;
}

$this->error('Syntax error');
}

/**
* generic value handler
*
* @access  private
*
* @return  mixed
*/
function val()
{
switch ($this->ch)
{
case '{':
return $this->obj();

case '[':
return $this->arr();

case '<':
return $this->assoc();

case '"':
return $this->str();

case '-':
return $this->num();

default:
return ($this->ch >= '0' && $this->ch <= '9') ? $this->num() : $this->word();
}
}

/**
* Gets the properties of the given object recursion
*
* @access private
*
* @return array
*/
function object_to_array($obj)
{
$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($_arr as $key => $val)
{
$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}

 

/**
* Escape special characters in variables recursively
*
* @access public
* @param mix $value
*
* @return mix
*/
function addslashes_deep($value)
{
if (empty($value))
{
return $value;
}
else
{
return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
}
}

/**
* Escape special characters of object member variables or arrays
*
* @access public
* @param mix $obj Object or array
* @author Xuan Yan
*
* @return mix Object or array
*/
function addslashes_deep_obj($obj)
{
if (is_object($obj) == true)
{
foreach ($obj AS $key => $val)
{
$obj->$key =$this-> addslashes_deep($val);
}
}
else
{
$obj = addslashes_deep($obj);
}

return $obj;
}

/**
* Recursively remove special characters in variables
*
* @access public
* @param mix $value
*
* @return mix
*/
function stripslashes_deep($value)
{
if (empty($value))
{
return $value;
}
else
{
return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
}
}


/**
* Transcode the parameters passed by JSON
*
* @param string $str
* @return string
*/
function json_str_iconv($str)
{
if (EC_CHARSET != 'utf-8')
{
if (is_string($str))
{
return ecs_iconv('utf-8', EC_CHARSET, $str);
}
elseif (is_array($str))
{
foreach ($str as $key => $value)
{
$str[$key] = json_str_iconv($value);
}
return $str;
}
elseif (is_object($str))
{
foreach ($str as $key => $value)
{
$str->$key = json_str_iconv($value);
}
return $str;
}
else
{
return $str;
}
}
return $str;
}

}

$string='{"email":"cc@126.com","content":"this is a  just a     test","type":"0","id":"13","enabled_captcha":"0","captcha":"","rank":"5"}';
$json=new JSON();

$cmt = $json->json_str_iconv($string);  //字符转码


$cmt  = $json->decode($cmt);    //解码

print_r($cmt);


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/444936.htmlTechArticlephp解析json数据二种实例方法 大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles