配色: 字号:
php语言的json实现
2016-10-26 | 阅:  转:  |  分享 
  
php语言的json实现

由于开发一个ajaxfilemanagerforweb开源项目,数据交换使用的json格式,后来发现在低版本的php上运行会有问题,仔细调试发现json_decode和json_encode无法正常工作,于是查阅资料,发现低版本的php没有实现这两个函数,为了兼容性,我只好自己实现一个php版的json编码解码代码,并保证和json2.js的一致,测试调试并通过,现在将其公布出来,供有相同需求的同学使用:


/

$base:$



$Author:$

BerlinQin



$History:base.js$

BerlinQin2011/5/15created



$contacted

webfmt@gmail.com

www.webfmt.com



/

/===========================================================================

license



1、OpenSourceLicenses

webfmtisdistributedundertheGPL,LGPLandMPLopensourcelicenses.

Thistriplecopyleftlicensingmodelavoidsincompatibilitywithotheropensourcelicenses.

TheseOpenSourcelicensesarespeciallyindicatedfor:

IntegratingwebfmtintoOpenSourcesoftware;

Personalandeducationaluseofwebfmt;

Integratingwebfmtincommercialsoftware,

takingcareofsatisfyingtheOpenSourcelicensesterms,

whilenotableorinterestedonsupportingwebfmtanditsdevelopment.



2、CommercialLicense–fbissourceClosedDistributionLicense-CDL

Formanycompaniesandproducts,OpenSourcelicensesarenotanoption.

ThisiswhythefbissourceClosedDistributionLicense(CDL)hasbeenintroduced.

Itisanon-copyleftlicensewhichgivescompaniescompletefreedom

whenintegratingwebfmtintotheirproductsandwebsites.

Thislicenseoffersaveryflexiblewaytointegratewebfmtinyourcommercialapplication.

ThesearethemainadvantagesitoffersoveranOpenSourcelicense:

Modificationsandenhancementsdoesn''tneedtobereleasedunderanOpenSourcelicense;

ThereisnoneedtodistributeanyOpenSourcelicensetermsalongsidewithyourproduct

andnoreferencetoithavetobedone;

Noreferencestowebfmthavetobedoneinanyfiledistributedwithyourproduct;

Thesourcecodeofwebfmtdoesn’thavetobedistributedalongsidewithyourproduct;

Youcanremoveanyfilefromwebfmtwhenintegratingitwithyourproduct.

TheCDLisalifetimelicensevalidforallreleasesofwebfmtpublishedduring

andbeforetheyearfollowww.baiyuewang.netwingitspurchase.

It''svalidforwebfmtreleasesalso.Itincludes1yearofpersonale-mailsupport.



/



functionjsonDecode($json)

{

$result=array();

try

{

if(PHP_VERSION_ID>50300)

{

$result=(array)json_decode($json);

}

else

{

$json=str_replace(array("\\\\","\\\""),array("\","""),$json);

$parts=preg_split("@(\"[^\"]\")|([\[\]\{\},:])|\s@is",$json,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);

foreach($partsas$index=>$part)

{

if(strlen($part)==1)

{

switch($part)

{

case"[":

case"{":

$parts[$index]="array(";

break;

case"]":

case"}":

$parts[$index]=")";

break;

case":":

$parts[$index]="=>";

break;

case",":

break;

default:

break;

}

}

}

$json=str_replace(array("\",""","$"),array("\\\\","\\\"","\\$"),implode("",$parts));

$result=eval("return$json;");

}

}

catch(Exception$e)

{

$result=array("error"=>$e->getCode());

}

return$result;

}



functionvalueTostr($val)

{

if(is_string($val))

{

$val=str_replace(''\"'',"\\\"",$val);

$val=str_replace("\\","\\\\",$val);

$val=str_replace("/","\\/",$val);

$val=str_replace("\t","\\t",$val);

$val=str_replace("\n","\\n",$val);

$val=str_replace("\r","\\r",$val);

$val=str_replace("\b","\\b",$val);

$val=str_replace("\f","\\f",$val);

return''"''.$val.''"'';

}

elseif(is_int($val))

returnsprintf(''%d'',$val);

elseif(is_float($val))

returnsprintf(''%F'',$val);

elseif(is_bool($val))

return($val?''true'':''false'');

else

return''null'';

}



functionjsonEncode($arr)

{

$result="{}";

try

{

if(PHP_VERSION_ID>50300)

{

$result=json_encode($arr);

}

else

{

$parts=array();

$is_list=false;

if(!is_array($arr))

{

$arr=(array)$arr;

}

$end=count($arr)-1;

if(count($arr)>0)

{

if(is_numeric(key($arr)))

{

$result="[";

for($i=0;$i
{

if(is_array($arr[$i]))

{

$result=$result.jsonEncode($arr[$i]);

}

else

{

$result=$result.valueTostr($arr[$i]);

}

if($i!=$end)

{

$result=$result.",";

}

}

$result=$result."]";

}

else

{

$result="{";

$i=0;

foreach($arras$key=>$value)

{

$result=$result.''"''.$key.''":'';

if(is_array($value))

{

$result=$result.jsonEncode($value);

}

else

{

$result=$result.valueTostr($value);

}

if($i!=$end)

{

$result=$result.",";

}

$i++;

}

$result=$result."}";

}

}

else

{

$result="[]";

}

}

}

catch(Exception$e)

{



}

return$result;

}

?>

如果使

献花(0)
+1
(本文系thedust79首藏)