我在反序列化序列化数据时遇到问题。
数据被序列化并保存在数据库中。
此数据包含一个上传的 .csv 网址,我想将其返回给 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);
数据:a:4:{i:0;O:27:"WpProQuiz_Model_AnswerTypes":10:{s:10:"��_mapper";N;s:10:"��_answer";s:16 :"测试答案 a";s:8:"��_html";b:0;s:10:"��_points";i:1;s:11:"��_正确";b: 1;s:14:"��_sortString";s:0:"";s:18:"��_sortStringHtml";b:0;s:10:"��_graded";b:0; s:22:"�*�_gradingProgression";s:15:"未评分}}
<td>
<?php
$ser = $quiz_name->answer_data;
$ser = str_replace("\0*\0_", 'key_', $ser);
$un = unserialize($ser);
$un = json_decode(json_encode($un), true);
$answers = array_column($un, 'key_answer');
foreach ($un as $row) {
echo '<li>' . $answers[] = $row['key_answer'] . '</p><br>';
}
?>
在线反序列化的有用工具 https://talktogeeks.com/unserialize.php