[12] | 1 | <?php |
---|
| 2 | /** |
---|
| 3 | * This class provides capabilities to parse json encoded rdf models. |
---|
| 4 | * |
---|
| 5 | * @package syntax |
---|
| 6 | * @author Philipp Frischmuth <philipp@frischmuth24.de> |
---|
| 7 | * @version $Id: JsonParser.php 555 2007-12-11 20:27:34Z p_frischmuth $ |
---|
| 8 | */ |
---|
| 9 | class JsonParser extends Object { |
---|
| 10 | |
---|
| 11 | /** |
---|
| 12 | * This method takes a json encoded rdf-model and a reference to aa (usually empty) MemModel, parses the json |
---|
| 13 | * string and adds the statements to the given MemModel. |
---|
| 14 | * |
---|
| 15 | * @param string $jsonString The string that contains the rdf model, encoded as a json-string. |
---|
| 16 | * @param MemModel $model A reference to the model, where to add the statements, usually an empty MemModel. |
---|
| 17 | */ |
---|
| 18 | public function generateModelFromString($jsonString, $model) { |
---|
| 19 | |
---|
| 20 | $jsonModel = array(); |
---|
| 21 | $jsonModel = json_decode($jsonString, true); |
---|
| 22 | |
---|
| 23 | // throws an excpetion if json model was corrupt |
---|
| 24 | if (!is_array($jsonModel)) { |
---|
| 25 | throw new Exception('error in json string'); |
---|
| 26 | } |
---|
| 27 | |
---|
| 28 | foreach ($jsonModel as $subject=>$remain) { |
---|
| 29 | foreach ($remain as $predicate=>$object) { |
---|
| 30 | $s = (strpos($subject, '_') === 0) ? new BlankNode(substr($subject, 2)) : new Resource($subject); |
---|
| 31 | $p = new Resource($predicate); |
---|
| 32 | |
---|
| 33 | foreach ($object as $obj) { |
---|
| 34 | if ($obj['type'] === 'uri') { |
---|
| 35 | $o = new Resource($obj['value']); |
---|
| 36 | } else if ($obj['type'] === 'bnode') { |
---|
| 37 | $o = new BlankNode(substr($obj['value'], 2)); |
---|
| 38 | } else { |
---|
| 39 | $dtype = (isset($obj['datatype'])) ? $obj['datatype'] : ''; |
---|
| 40 | $lang = (isset($obj['lang'])) ? $obj['lang'] : ''; |
---|
| 41 | |
---|
| 42 | $oVal = $obj['value']; |
---|
| 43 | |
---|
| 44 | $o = new Literal($oVal, $lang); |
---|
| 45 | $o->setDatatype($dtype); |
---|
| 46 | } |
---|
| 47 | |
---|
| 48 | $model->add(new Statement($s, $p, $o)); |
---|
| 49 | } |
---|
| 50 | } |
---|
| 51 | } |
---|
| 52 | } |
---|
| 53 | } |
---|
| 54 | ?> |
---|