我如何反序列化,然后将结果多维数组转换为纯文本,剥离代码?



在此事先感谢您的帮助。我正试图将一些产品规格从Wordpress网站导出到允许使用PHP过滤器的WP All export电子表格中,我们希望它可以导出为易于阅读的文本。规范存在于自定义WP字段中,该字段作为序列化数组导出。我完全不精通PHP,但我认为我需要将WP字段内容反序列化为数组,然后我需要将结果数组转换为尽可能接近简单字符串(尽管规范类别之间的换行是理想的)。这可能吗?下面是我需要转换的字段之一的示例:


: 3:{: 6:"header" b: 0;销售:7:"caption"; b: 0;销售:4:"body";答:4:{我:0;答:2:{0;有:1:{:1:"c"销售:9:"Materials";}我:1;答:1:{:1:"c"销售:26:"钢alloy";}}我:1;答:2:{0;有:1:{:1:"c"销售:6:"Weight";}我:1;答:1:{:1:"c"销售:18:"2.25 lbs";}}我:2;答:2:{0;有:1:{:1:"c"销售:6:"Length";}我:1;答:1:{:1:"c"销售:16:"6.32in";}}我:3;:2:{0;有:1:{:1:"c"销售:20:"适用Standards";}我:1;答:1:{:1:"c"销售:46:"符合OSHA xxx, ANSI xxx";}}}}


. .理想情况下看起来像这样:


材料:钢合金,
重量:2.25磅,
长度:6.32英寸,
适用标准:符合OSHA xxx, ANSI xxx


序列化的数据不知何故变得畸形了。几个字段有一个不正确的长度,例如钢合金是11个字符,但你的字符串说26。我怀疑你在发布前手动编辑了数据。以下是更正后的版本:

a:3:{s:6:"header";b:0;s:7:"caption";b:0;s:4:"body";a:4:{i:0;a:2:{i:0;a:1:{s:1:"c";s:9:"Materials";}i:1;a:1:{s:1:"c";s:11:"Steel alloy";}}i:1;a:2:{i:0;a:1:{s:1:"c";s:6:"Weight";}i:1;a:1:{s:1:"c";s:8:"2.25 lbs";}}i:2;a:2:{i:0;a:1:{s:1:"c";s:6:"Length";}i:1;a:1:{s:1:"c";s:7:"6.32 in";}}i:3;a:2:{i:0;a:1:{s:1:"c";s:20:"Applicable Standards";}i:1;a:1:{s:1:"c";s:24:"Meets OSHA xxx, ANSI xxx";}}}}

检索数据相当简单。你可以根据自己的需要调整:

$unserialized = unserialize($your_string);
foreach ($unserialized['body'] as $item) {
echo $item[0]['c'] . ': ' . $item[1]['c'] . '<br />;
}

输出:

Materials: Steel alloy
Weight: 2.25 lbs
Length: 6.32 in
Applicable Standards: Meets OSHA xxx, ANSI xxx

你可以这样做:

<?php
function parseCrazy($crazy){
$o = new StdClass;
if(preg_match_all('/(?<=")(?:[A-Z]|[0-9]).+(?=")/U', $crazy, $m)){
$all = $m[0];
for($i=0,$n=1,$l=count($all); $i<$l; $i+=2,$n+=2){
$o->{$all[$i]} = $all[$n];
}
}
return $o;
}
$crazy = 'a:3:{s:6:"header";b:0;s:7:"caption";b:0;s:4:"body";a:4:{i:0;a:2:{i:0;a:1:{s:1:"c";s:9:"Materials";}i:1;a:1:{s:1:"c";s:26:"Steel alloy";}}i:1;a:2:{i:0;a:1:{s:1:"c";s:6:"Weight";}i:1;a:1:{s:1:"c";s:18:"2.25 lbs";}}i:2;a:2:{i:0;a:1:{s:1:"c";s:6:"Length";}i:1;a:1:{s:1:"c";s:16:"6.32 in";}}i:3;a:2:{i:0;a:1:{s:1:"c";s:20:"Applicable Standards";}i:1;a:1:{s:1:"c";s:46:"Meets OSHA xxx, ANSI xxx";}}}}';
$o = parseCrazy($crazy); // access like $o->Materials, $o->Weight, $o->Length, $o->{'Applicable Standards'}
foreach($o as $k => $v){
$a[] = $k.':'.$v;
}
echo join('<br />', $a);
?>

相关内容

  • 没有找到相关文章