unserializ不适合大文本

时间:2013-07-20 05:35:43

标签: php serialization

我有一个包含大文本字段的类,其中包含可能是合同或业务表单的文本。到目前为止,这是我的代码:

public function saveAction()
{
    if (isset ($_POST['Save']) && $this->isPostSafe()) {
        $form = Form::getPostObject();
        $form->text = addslashes($form->text);
        var_dump($form);
        $form->save($this->_databaseConnection);
    }
    $this->redirect('/forms');
}

public function __construct()
{
    $company_info = Config::get('Company');
    foreach ($company_info as $setting => $value) {
        $this->variables[$setting] = $value;
    }
    $this->variables = serialize($this->variables);
}

public function set($name, $value)
{
    $values = unserialize($this->variables);
    $values[$name] = $value;
    $this->variables = serialize($this->variables);
}

public function render()
{
    var_dump($this->variables);
    $values = unserialize($this->variables);

    foreach ( $values as $key => $value) {
        $from = "[@$key]";
        $this->text = str_replace($from, $value, $this->text);
    }
    return $template;
}

问题是var_dump给了我反序列化的字符串,我尝试了base64_encode并且它没有解决问题

2 个答案:

答案 0 :(得分:1)

您的设置功能错误

public function set($name, $value)
{
    $values = unserialize($this->variables);
    $values[$name] = $value;
    $this->variables = serialize($this->variables);
}

应该是

public function set($name, $value)
{
    $values = unserialize($this->variables);
    $values[$name] = $value;
    $this->variables = serialize($values);
}

答案 1 :(得分:0)

我的建议是重写代码...基本上你只想处理保存对象时的序列化和加载对象时的反序列化

public function __construct()
{
    $company_info = Config::get('Company');
    foreach ($company_info as $setting => $value) {
        $this->variables[$setting] = $value;
    }
}

public function set($name, $value)
{
      $this->variables[$name] = $value;
}

public function get($name){
      return isset($this->variables[$name])?$this->variables[$name]:"";
}

public function render()
{
    // for debugging
    var_dump($this->variables);

    foreach ( $this->variabes as $key => $value) {
        $from = "[@$key]";
        $this->text = str_replace($from, $value, $this->text);
    }
    return $template;
}

public function saveAction()
{
    if (isset ($_POST['Save']) && $this->isPostSafe()) {
        $form = Form::getPostObject();
        $form->text = addslashes($form->text);
        var_dump($form);
        $serialized = serialize($this->variables); // serialize before you save
        $form->save($this->_databaseConnection);
    }
    $this->redirect('/forms');
}