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 says: Unable to parse at line 11 (near " 0KHQtNC10LvQsNGC0Ywg0LPRgNCw0LzQvtGC0L3Ri9C5INCy0L3QtdGI0L3Q").
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.
Aren't sfYaml and Spyc reliable enough?
Any suggestions what to do? Which parser or trick could I use to work with this database from PHP?
Here's my solution:
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