Since I didn't find a way to properly transform JavaScript object to JSON with PHP, I wrote a snippet.
Lets assume the following excerpt from Google Fonts JavaScript API:
WebFontConfig = {
google: { families: [ 'Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic:latin,latin-ext' ] }
};
This, given straight to PHP's json_decode
will null
out and JSONLint will say it's invalid.
Since I need this data in JSON after the template has been parsed (working on an exporter), I wrote this snippet (which double-quotes the hell out of this one):
// gather WebFontConfig arrays
$webfonts = preg_match_all('/(WebFontConfig\s*?=\s*?)\{(.+?)(\};)/s', $scriptData, $fontdata, PREG_SET_ORDER);
// kids, dont do this at home
foreach ($fontdata as $founddata)
{
$original = $founddata[0];
$WFCVariable = $founddata[1];
// leave outer braces only
$usable = str_replace($WFCVariable, '', $original);
$usable = trim($usable, ';');
// transform keys into double-quoted keys
$usable = preg_replace('/(\w+)(:\s*?)(\{|\[)/im', '"$1"$2$3', $usable);
// prepare to transform array wrapping single quotes to double quotes
$lookups = array(
'/(\[)(\s*?)(\')/',
'/(\')(\s*?)(\])/'
);
$replace = array(
'$1$2"',
'"$2$3'
);
$usable = preg_replace($lookups, $replace, $usable);
// decode
$jsoned = json_decode($usable);
// and check
var_dump($jsoned);
}
$scriptData
essentially is the above JavaScript object trim-extracted out of my template through DOMDocument
.. DOMNode->nodeValue
.
There is no problem with the snippet, it converts my data into PHP array without problems.
My concern, though, is, whether this is the most optimal way of doing it?