This repository has been archived on 2018-10-11. You can view files and clone it, but cannot push or open issues or pull requests.
sleepy/Sleepy/Type/XML.php

100 lines
1.8 KiB
PHP
Raw Permalink Normal View History

2014-05-14 10:32:31 -04:00
<?php
/**
* Sleepy - a REST framework
*
*
* A PHP Rest Framework valuing convention over configuration,
* but aiming to be as flexible as possible
*
* @author Timothy J. Warren
*/
namespace Sleepy\Type;
use \Sleepy\Core\Abstracts\Type as aType;
/**
* Implementation of XML data type
*/
class XML extends aType {
/**
* The mime type for output
*
* @var string
*/
protected $mime = 'application/xml';
/**
* Convert php array/object to xml
*
* @param array|object $data
* @return string
*/
public function serialize($data = NULL)
{
$this->set_data($data);
$xmlObject = new \SimpleXMLElement('<?xml version="1.0"?><root></root>');
$this->array_to_xml($data, $xmlObject);
return $xmlObject->asXML();
}
/**
* Convert xml to php data
*
* @param string $string
* @return object
*/
public function unserialize($string)
{
$xml = \simplexml_load_string($string);
$json = json_encode($xml);
$object = json_decode($json);
return $object;
}
/**
* Recursively generate xml from an array or object
*
* @param array|object $array
* @param \SimpleXMLElement $xmlObject
*/
private function array_to_xml($array, \SimpleXMLElement &$xmlObject)
{
foreach($array as $key => $val)
{
$key = $this->fix_xml_key($key);
if ( ! is_scalar($val))
{
$subnode = $xmlObject->addChild($key);
$this->array_to_xml($val, $subnode);
}
else
{
$xmlObject->addChild($key, \htmlspecialchars($val, ENT_XML1, 'UTF-8'));
}
}
}
/**
* Make an invalid xml key more valid
*
* @param string $key
* @return string
*/
private function fix_xml_key($key)
{
if (is_numeric($key))
{
$key = "item_{$key}";
}
return preg_replace('`[^a-zA-Z0-9_:]`', '_', $key);
}
}
// End of Type/XML.php