本文介绍了如何在 PHP 中解析 Ruby 的 YAML(sfYaml 和 Spyc 不会做对)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the values like following in MySQL (made by 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").

sfYaml says: Unable to parse at line 11 (near " 0KHQtNC10LvQsNGC0Ywg0LPRgNCw0LzQvtGC0L3Ri9C5INCy0L3QtdGI0L3Q").

Spyc 将-"项添加到与 author_id、status_id 等相同的级别.看起来很合理(因为没有空格),但是 Ruby 的 YAML 可以很好地解释它.Spyc 也忽略 base64.

Spyc adds "-" items into the same level as author_id, status_id and so on. Looks reasonable (because no spacing), but it is being interpreted well by Ruby's YAML. Spyc also ignores base64.

sfYaml 和 Spyc 还不够可靠吗?

Aren't sfYaml and Spyc reliable enough?

有什么建议吗?我可以使用哪种解析器或技巧来处理 PHP 中的这个数据库?

Any suggestions what to do? Which parser or trick could I use to work with this database from PHP?

推荐答案

这是我的解决方案:

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

这篇关于如何在 PHP 中解析 Ruby 的 YAML(sfYaml 和 Spyc 不会做对)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 19:27