Use a Perl's Data::Dumper format array in PHP

对着背影说爱祢 提交于 2019-12-11 23:28:05

问题


I need to acces an array wich is outputed by Perl's Data::Dumper.
Array is in a raw file, and I need to acces it with php.
Array is formated as this:

$stats = {
  'days' => 25,
  'lengths' => {
    'Piwee' => 269,
    'Jeanne-' => 904,
    'kaAnar' => 340,
[... Very Big ARRAY....]

I found this solution on here, but i dont want to use eval() because this array will have user-input data. Since i will always need to eval() output in case of a str_replace solution, i think i need to find another way to do it.
Maybe convert to XML or by direct PHP parsing ?
I'm not sure about what would be the best solution here.

A perl / PHP / bash solution would be okay

note 1: I cant edit the Perl code that output this raw file
note 2: I dont code in Perl so i dont know how to work with such datas


回答1:


Don't use Data::Dumper to export your data. It's primarily for debugging purposes, not for data serialisation, and especially not for input to an alien language

Use the Perl JSON module's encode_json call to create a JSON string from the Perl hash, and PHP's json_decode to convert it into a PHP associative array

For instance, say your output from Data::Dumper is in file stats.data, then a short Perl program like this will print the JSON equivalent to STDOUT

use strict;
use warnings 'all';

use JSON;

print encode_json( do 'stats.data' or die $! ), "\n";

output

{"lengths":{"Jeanne-":904,"Piwee":269,"kaAnar":340},"days":25}


来源:https://stackoverflow.com/questions/35690380/use-a-perls-datadumper-format-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!