Passing Structured Data from Perl to PHP
After writing many lines of Perl to decode data returned from database queries which must then be passed back to PHP, I found JSON conversion routines which are much faster and more reliable. In addition, unlike my awkward Perl, they work!
::::::::::::::
test.pl
::::::::::::::
#!/usr/bin/perl
use strict;
use JSON::XS;
# Thanks to: http://stackoverflow.com/questions/8463919/how-to-convert-a-simple-hash-to-json-in-perl
my $json=JSON::XS->new->utf8->pretty->allow_nonref;
my %data=('one',1,'two',"bee's",'three',0,'four',('a','monkey','b','cat'));
my $json_text=$json->encode(\%data);
# Escape the single quotes
$json_text=~s/(')/\\$1/g;
# Remove carriage returns
$json_text=~s/(\n)//g;
print<<RETURN;
json=$json_text
RETURN
::::::::::::::
test.php
::::::::::::::
<?php
include 'Zend/Json.php';
$aResult=null;
$aResponseLines=$aResult=array();
$sResponse=`perl test.pl`;
$aResponseLines=explode("\n",$sResponse);
if (count($aResponseLines)>0)
foreach ($aResponseLines as $k => $v)
{
$e=strpos($v,'=');
if ($e!==false)
$aResult[substr($v,0,$e)]=substr($v,$e+1);
}
var_dump($aResult);
var_dump(Zend_Json::decode($aResult['json']));
Print article | This entry was posted by elvis on 06/14/12 at 07:48:00 am . Follow any responses to this post through RSS 2.0. |