PHP取消序列化数据的序列化


PHP unserialize serialized data

我在取消序列化数据的序列化时遇到问题。

数据被序列化并保存在数据库中。

此数据包含一个上传的.csv url,我想将其返回给fgetcsv。

fgetcsv需要一个数组,现在给出了一个字符串,所以我需要取消数据的序列化,但这会给我带来错误。

我在网上找到的http://davidwalsh.name/php-serialize-unserialize-issues但这似乎不起作用。所以我希望有人能告诉我哪里错了:

错误如下:

Notice: unserialize() [function.unserialize]: Error at offset 0 of 1 bytes in /xxx/public_html/multi-csv-upload.php on line 163

我发现这意味着序列化数据中存在某些字符,使文件在未序列化(",',:,;) 后损坏

第163行:

jj_readcsv(unserialize ($value[0]),true);` // this reads the url of the uploaded csv and tries to open it.

以下是使数据序列化的代码:

update_post_meta($post_id, 'mcu_csv', serialize($mcu_csv));

这是WordPress

以下是的输出

echo '<pre>';
print_r(unserialize($value));
echo '</pre>';

Array ( [0] => http://www.domain.country/xxx/uploads/2014/09/test5.csv )

在我看来,这里应该没有什么问题。

有人知道我该如何将其取消序列化以便使用它吗?以下是我最近做的。。。

public function render_meta_box_content($post)
{
    // Add an nonce field so we can check for it later.
    wp_nonce_field('mcu_inner_custom_box', 'mcu_inner_custom_box_nonce');
    // Use get_post_meta to retrieve an existing value from the database.
    $value = get_post_meta($post->ID, 'mcu_images', true);
    echo '<pre>';
        print_r(unserialize($value));
    echo '</pre>';
    ob_start();
    jj_readcsv(unserialize ($value[0]),true);
    $link = ob_get_contents();
    ob_end_clean();
    $editor_id = 'my_uploaded_csv';
    wp_editor( $link, $editor_id );


    $metabox_content = '<div id="mcu_images"></div><input type="button" onClick="addRow()" value="Voeg CSV toe" class="button" />';
    echo $metabox_content;
    $images = unserialize($value);
    $script = "<script>
        itemsCount= 0;";
    if (!empty($images))
    {
        foreach ($images as $image)
        {
            $script.="addRow('{$image}');";
        }
    }
    $script .="</script>";
    echo $script;
}
function enqueue_scripts($hook)
{
    if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
        return;
    wp_enqueue_script('mcu_script', plugin_dir_url(__FILE__) . 'mcu_script.js', array('jquery'));
}

您正试图访问序列化字符串的第一个元素:

jj_readcsv(unserialize ($value[0]),true);

由于字符串本质上是字符数组,您正试图取消序列化字符串的第一个字符的序列化。

您需要先取消序列化,然后访问数组元素:

//php 5.4+
jj_readcsv(unserialize ($value)[0],true);
//php < 5.4
$unserialized = unserialize ($value);
jj_readcsv($unserialized[0],true);

或者,如果只有一个元素,不要将数组存储在第一位,只需保存url字符串,它不需要序列化:

//save
update_post_meta($post_id, 'mcu_csv', $mcu_csv[0]);
//access
jj_readcsv($value, true);