johan855 johan855 - 4 months ago 17
Smarty Question

Creating a URL encoded string in smarty

I am trying to create a string of values taken from variables in the backend with the following structure:


Before encoding:


transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;
transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;



After encoding:


transaction_id%3D0815%2F2009%3Btransaction_cid%3D54AB%3Bitem_id%3D40216304 5080%3Bitem_value%3D25.20%3Bitem_quantity%3D1%3Bitem_id%3D847163029054%3Bi tem_value%3D16.81%3Bitem_quantity%3D2


I have managed to create an array with the necessary data in this form:

'[{"transaction_id":"233684","transaction_cid":"d2871c13c507583048d8ecf4a16f94c0","i tem_id":"3524","item_value":"4915.13","item_quantity":"1"}]',


But what I need is all these elements of the array in a url encoded string.

I am out of ideas since all that I try seems to not work.

Using JSON.stringify keeps the
":"
and the
"""
, using alert() or join also keeps the
":"
and is not performant.

Example array:


arr : {key1: 'a', key2:'b', key3:'c'}


non encoded result:


str : 'key1=a;key2=b;key3=c'


desired result:


str : 'key1%3Da%3Bkey2%3Db%3Bkey3%3Dc'


Here is my code so far:

[{foreach from=$orderArticles item="currOrderArticle"}]
[{assign var="currBasePrice2" value=$currOrderArticle->getBasePrice()}]

products_info.push(
{
transaction_id: '[{$order->oxorder__oxordernr->value}]',
transaction_cid: '[{$order->oxorder__oxuserid->value}]',
item_id: '[{$currOrderArticle->oxorderarticles__oxartnum->value}]',
item_value: '[{$basket->getDiscountedNettoPrice()}]',
item_quantity: '[{$currOrderArticle->oxorderarticles__oxamount->value}]'
});

[{/foreach}]


Any ideas on how this can be accomplished?

Answer

You can combine json_encode (or serialize if you only need to use it in php) and escape:

{$arr|json_encode|escape:'url'}

Also, if you want to make the string shorter you can use compression:

{$arr|json_encode|gzcompress|base64_encode|escape:'html'}

Though that may be a bit overkill for short arrays and you'll have to base64_decode, gzuncompress and json_decode the string when you receive it.