dongshanxiao7328 2013-09-08 22:19
浏览 36
已采纳

如何将序列化数组传递给Symfony2 Command

I create a symfony2 command with one argument. This argument is the result of serialize($array) function.

But, inside the command I'm not able to unserialize() the received argument, i always got an error:

Notice: unserialize(): Error at offset 5 of 48 bytes in ...

This is a example of the array i want to send to the command:

$array = array('key1' => '$value1', 'key2' => '$value2')

When i serialize the array (serialize($array)) this is the result:

a:2:{s:4:"key1";s:7:"$value1";s:4:"key2";s:7:"$value2";} 

I was thinking: maybe the problem is due to double quotes in the string (remember, is to send to a command as parameter), then, i apply the addslashes function:

addslashes(serialize($array)) 

This is the result:

a:2:{s:4:\"key1\";s:7:\"$value1\";s:4:\"key2\";s:7:\"$value2\";}

but im still receiving the same error when i try to unserialize the string inside the command execute() function.

Any idea?

  • 写回答

1条回答 默认 最新

  • douci1541 2013-09-08 23:46
    关注

    SOLVED!!! the problem is with the operative system command line and the double quotes. There is a way to serialize the array and avoid double quotes as parameter in the command: encoding base64.

    The solution is to encode the serialized array:

    $serialized = serialize(array('key1' => 'value1', 'key2' => 'value2'));
    //$serialized => a:2:{s:4:"key1";s:6:"value1";s:4:"key2";s:6:"value2";}
    
    $base64 = base64_encode($serialize);
    //$base64 => YToyOntzOjQ6ImtleTEiO3M6NjoidmFsdWUxIjtzOjQ6ImtleTIiO3M6NjoidmFsdWUyIjt9 
    

    As you can see there is no quotes in $base64(that's one of the goals of base64_encode() ) Then, you can easily decode the string with base64_decode

    $serialized = base64_decode($base64);
    //$serialized => a:2:{s:4:"key1";s:6:"value1";s:4:"key2";s:6:"value2";}
    
    $array = unserialize($serialized);
    //$array => array('key1' => 'value1', 'key2' => 'value2')
    

    I hope this help somebody

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比