1

我在 MySQL 中具有以下值(由 ChiliProject 制作):

--- 
author_id: 
- 0
- 1
status_id: 
- 0
- 1
subject: 
- ""
- !binary |
  0KHQtNC10LvQsNGC0Ywg0LPRgNCw0LzQvtGC0L3Ri9C5INCy0L3QtdGI0L3Q
  uNC5INCy0LjQtCDQtNC70Y8g0LjQvNC10Y7RidC10LPQvtGB0Y8=

start_date: 
- 
- 2012-04-30
priority_id: 
- 0
- 4
tracker_id: 
- 0
- 2
description: 
- 
- ""
project_id: 
- 0
- 2
created_on: 
- 
- 2012-04-30 17:51:08.596410 +04:00

sfYaml 说:无法在第 11 行解析(靠近“0KHQtNC10LvQsNGC0Ywg0LPRgNCw0LzQvtGC0L3Ri9C5INCy0L3QtdGI0L3Q”)。

Spyc 将“-”项添加到与 author_id、status_id 等相同的级别。看起来很合理(因为没有间距),但是 Ruby 的 YAML 很好地解释了它。Spyc 也忽略了 base64。

sfYaml 和 Spyc 还不够可靠吗?

有什么建议该怎么做吗?我可以使用哪个解析器或技巧从 PHP 处理这个数据库?

4

1 回答 1

1

这是我的解决方案:

RubyYaml.php:

<?php

class RubyYaml
{
    static public function parse($data)
    {
        $descriptorSpec = array(
            0 => array("pipe", "r"),  // stdin
            1 => array("pipe", "w"),  // stdout
            //2 => array("pipe", "a"),  // stderr
        );

        $process = proc_open('ruby '.__DIR__.'/yaml2json.rb', $descriptorSpec, $pipes);

        if (!is_resource($process))
            throw new CException('Cannot start YAML parser');

        fwrite($pipes[0], $data);
        fclose($pipes[0]);

        $json = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        proc_close($process);

        $result = json_decode($json, true);
        if ($result === null) // Don't your YAMLs contain plain NULL ever?
            throw new CException('YAML parsing failed: '.$json);

        return $result;
    }
}

yaml2json.rb:

require "json"
require 'yaml'

def recursion(v)

  if v.class == String
    v.force_encoding('utf-8')

  elsif v.class == Array
    v.each do |vv|
      recursion(vv)
    end

  elsif v.class == Hash
    v.each do |k, vv|
      recursion(vv)
    end

  end

end


thing = YAML.load(STDIN.read)

recursion(thing)

puts thing.to_json
于 2013-04-25T12:00:51.887 回答