Skip to content
This repository has been archived by the owner on Jan 23, 2021. It is now read-only.

Commit

Permalink
Merge pull request #1 from jameshalsall/hotfix/empty-text-nodes
Browse files Browse the repository at this point in the history
Fixing logic where empty text nodes would be created as empty JSON #text...
  • Loading branch information
markwilson committed Jul 17, 2014
2 parents 9f57b6b + 45e13dd commit 00971b2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
5 changes: 4 additions & 1 deletion src/MarkWilson/XmlToJson/Tests/XmlToJsonConverterTest.php
Expand Up @@ -41,7 +41,10 @@ public function getConvertData()
], [
'<Element><SubElement>Value 1</SubElement><SubElement>Value 2</SubElement></Element>',
'{"Element":{"SubElement":["Value 1","Value 2"]}}'
],
], [
'<Metadata><SubscriptionCreate url="http://www.google.com/home#anchor"/><SubscriptionValidate url="https://yahoo.com/login" required="N"/><Studio email="studio@gmail.com" phone="020 7607 3200"/></Metadata>',
'{"Metadata":{"SubscriptionCreate":{"-url":"http:\/\/www.google.com\/home#anchor"},"SubscriptionValidate":{"-url":"https:\/\/yahoo.com\/login","-required":"N"},"Studio":{"-email":"studio@gmail.com","-phone":"020 7607 3200"}}}'
]
];
}
}
8 changes: 4 additions & 4 deletions src/MarkWilson/XmlToJson/XmlToJsonConverter.php
Expand Up @@ -19,7 +19,7 @@ class XmlToJsonConverter
*/
public function convert(\SimpleXMLElement $xml)
{
return json_encode([$xml->getName() => $this->getData($xml)]);
return json_encode(array($xml->getName() => $this->getData($xml)));
}

/**
Expand All @@ -33,7 +33,7 @@ public function convert(\SimpleXMLElement $xml)
*/
private function getData(\SimpleXMLElement $xml)
{
$data = [];
$data = array();

// loop through the attributes and append them to the data array with '-' prefix on keys
foreach ($xml->attributes() as $key => $value) {
Expand All @@ -52,7 +52,7 @@ private function getData(\SimpleXMLElement $xml)
if (is_array($data[$key])) {
$data[$key][] = $childData;
} else {
$data[$key] = [$data[$key], $childData];
$data[$key] = array($data[$key], $childData);
}
} else {
$data[$key] = $childData;
Expand All @@ -65,7 +65,7 @@ private function getData(\SimpleXMLElement $xml)
// check if this is just a single value element, i.e. <Element>Value</Element>
if (count($data) === 0) {
$data = $value;
} else {
} elseif (strlen((string) $xml)) {
$data['#text'] = (string)$xml;
}
}
Expand Down

0 comments on commit 00971b2

Please sign in to comment.