Skip to content
Snippets Groups Projects
Commit 32555b0a authored by Kevin Abel's avatar Kevin Abel
Browse files

Add class to support converting array to JSON and XML.

To be used for converting raw data into a CAP formatted file.
parent 249bf5b5
No related branches found
No related tags found
1 merge request!1Implement RAVE RSS feed a source of proxied alerts
<?php
class UNL_Alert_ArrayObject extends ArrayObject
{
/**
* Returns an XML string representation of this object's internal data
*
* @param string $rootName The element name for the root wrapper element
* @param string $rootNS The default namespace for the root element
* @param string $numericName The element name to use for top level numeric array indicies
* @return string
*/
public function toXML($rootName = 'root', $rootNS = '', $numericName = 'item')
{
$document = new DOMDocument('1.0', 'UTF-8');
if ($rootNS) {
$root = $document->createElementNS($rootNS, $rootName);
} else {
$root = $document->createElement($rootName);
}
$document->appendChild($root);
$data = $this->getArrayCopy();
$this->appendToXml($document, $root, $data, $numericName);
return $document->saveXML();
}
/**
* Iterates over $data array and appends elements created with $document
* to the $node. If the array is numerically indexed, the $rootName will
* be used as the element name.
*
* @param DOMDocument $document
* @param DOMNode $node
* @param array $data
* @param string $rootName
*/
protected function appendToXml($document, $node, $data, $rootName)
{
$isAssoc = !count(array_filter(array_keys($data), 'is_numeric'));
foreach ($data as $key => $value) {
$childName = $key;
if (is_numeric($key)) {
$childName = $rootName;
if ($isAssoc) {
continue;
}
}
if (is_array($value)) {
if ($isAssoc) {
$child = $node;
} else {
$child = $document->createElement($childName);
$node->appendChild($child);
}
$this->appendToXml($document, $child, $value, $childName);
} else {
$child = $document->createElement($childName, $value);
$node->appendChild($child);
}
}
}
/**
* Returns a JSON encoded string representation of this object's internal data
*
* @param string $rootWrapper
* @return string
*/
public function toJSON($rootWrapper = null)
{
$data = $this->getArrayCopy();
if (empty($data)) {
$data = new stdClass();
} elseif (!empty($rootWrapper)) {
$data = array($rootWrapper => $data);
}
return json_encode($data);
}
}
\ No newline at end of file
  • Did you write this yourself? It looks good, but it scares me that there are no tests. How do you know this works 100% of the time?

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment