2013-09-08 22:19
浏览 31

如何将序列化数组传递给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:


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:


This is the result:


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

Any idea?

图片转代码服务由CSDN问答提供 功能建议

我创建一个带有一个参数的symfony2命令。 这个参数是serialize($ array)函数的结果。< / p>


 注意:  unserialize():错误在48个字节的偏移量为5的... 


  $ array = array('key1'=&gt;'$ value1','key2'=&gt;'$ value2')

当我序列化数组(serialize($ array))时,这就是结果:

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

我在想:也许是问题 是由于字符串中的双引号(记住,是作为参数发送到命令),然后,我应用addslashes函数:

  addslashes(serialize($ array)  )


  a:2:{s:4:\“key1 \  “; S:7:\” $值1 \“; S:4  :\“key2 \”; s:7:\“$ value2 \”;} 

但是当我尝试反序列化字符串时我仍然收到相同的错误 命令execute()函数内部。


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    打赏 评论

相关推荐 更多相似问题