I've retrieved a PHP script that converts an XML file to JSON. This script is interesting because it correctly handles namespaces. I'd like to convert it to JavaScript so I can use it with Purebasic. Unfortunately, I have almost no knowledge of PHP and JavaScript, so I'm looking for help. Could someone give me a hand?
Thanks in advance.
Code: Select all
<?php
/**
* @param string $xml XML code to convert to JSON
* @param array $options Options of the API to change JSON output
*
* @return array The JSON response
*/
function xmlToArray($xml, $options = [])
{
$defaults = [
'namespaceRecursive' => false, // Get XML doc namespaces recursively
'removeNamespace' => true, // Remove namespace from resulting keys
'namespaceSeparator' => ':', // Change separator to something other than a colon
'attributePrefix' => '', // Distinguish between attributes and nodes with the same name
'alwaysArray' => [], // Array of XML tag names which should always become arrays
'autoArray' => true, // Create arrays for tags which appear more than once
'textContent' => 'text', // Key used for the text content of elements
'autoText' => true, // Skip textContent key if node has no attributes or child nodes
'keySearch' => false, // (Optional) search and replace on tag and attribute names
'keyReplace' => false, // (Optional) replace values for above search values
];
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces($options['namespaceRecursive']);
$namespaces[''] = null; // Add empty base namespace
// Get attributes from all namespaces
$attributesArray = [];
foreach ($namespaces as $prefix => $namespace) {
if ($options['removeNamespace']) {
$prefix = '';
}
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
// (Optional) replace characters in attribute name
if ($options['keySearch']) {
$attributeName = str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
}
$attributeKey = $options['attributePrefix'] . ($prefix ? $prefix . $options['namespaceSeparator'] : '') . $attributeName;
$attributesArray[$attributeKey] = (string) $attribute;
}
}
// Get child nodes from all namespaces
$tagsArray = [];
foreach ($namespaces as $prefix => $namespace) {
if ($options['removeNamespace']) {
$prefix = '';
}
foreach ($xml->children($namespace) as $childXml) {
// Recurse into child nodes
$childArray = xmlToArray($childXml, $options);
$childTagName = key($childArray);
$childProperties = current($childArray);
// Replace characters in tag name
if ($options['keySearch']) {
$childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
}
// Add namespace prefix, if any
if ($prefix) {
$childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
}
if (!isset($tagsArray[$childTagName])) {
// Only entry with this key
// Test if tags of this type should always be arrays, no matter the element count
$tagsArray[$childTagName] = in_array($childTagName, $options['alwaysArray'], true) || !$options['autoArray'] ? [$childProperties] : $childProperties;
} elseif (is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName]) === range(0, count($tagsArray[$childTagName]) - 1)) {
// Key already exists and is integer indexed array
$tagsArray[$childTagName][] = $childProperties;
} else {
// Key exists so convert to integer indexed array with previous value in position 0
$tagsArray[$childTagName] = [$tagsArray[$childTagName], $childProperties];
}
}
}
// Get text content of node
$textContentArray = [];
$plainText = trim((string) $xml);
if ($plainText !== '') {
$textContentArray[$options['textContent']] = $plainText;
}
// Stick it all together
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || $plainText === '' ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
// Return node as array
return [
$xml->getName() => $propertiesArray,
];
}
$xml = '<GPO xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.microsoft.com/GroupPolicy/Settings">
<Identifier>
<Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{BCEBAC67-B698-4724-9694-18BEF3B81917}</Identifier>
<Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">mdv.lan</Domain>
</Identifier>
<Name>GPO Mappage Eleves</Name>
<IncludeComments>true</IncludeComments>
<CreatedTime>2021-03-05T11:37:23</CreatedTime>
<ModifiedTime>2023-09-18T12:31:13</ModifiedTime>
<ReadTime>2024-10-09T12:41:32.6928166Z</ReadTime>
<FilterDataAvailable>true</FilterDataAvailable>
<Computer>
<VersionDirectory>0</VersionDirectory>
<VersionSysvol>0</VersionSysvol>
<Enabled>true</Enabled>
</Computer>
<User>
<VersionDirectory>62</VersionDirectory>
<VersionSysvol>62</VersionSysvol>
<Enabled>true</Enabled>
<ExtensionData>
<Extension xmlns:q1="http://www.microsoft.com/GroupPolicy/Settings/DriveMaps" xsi:type="q1:DriveMapSettings">
<q1:DriveMapSettings clsid="{8FDDCC1A-0C3C-43cd-A6B4-71A6DF20DA8C}">
<q1:Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="T:" status="T:" image="2" changed="2021-08-27 08:07:36" uid="{FCE5D214-48DD-4F86-91F2-DBEFDD9256CD}">
<q1:GPOSettingOrder>1</q1:GPOSettingOrder>
<q1:Properties action="U" thisDrive="SHOW" allDrives="NOCHANGE" userName="" path="\\192.168.0.1\Commun" label="Echange" persistent="0" useLetter="1" letter="T" />
<q1:Filters />
</q1:Drive>
<q1:Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="S:" status="S:" image="2" changed="2021-08-27 08:07:29" uid="{EBE52889-52DD-4C22-830F-B5EF7BCB31B1}">
<q1:GPOSettingOrder>2</q1:GPOSettingOrder>
<q1:Properties action="U" thisDrive="SHOW" allDrives="NOCHANGE" userName="" path="\\192.168.0.1\Groupes" label="Groupes" persistent="0" useLetter="1" letter="S" />
<q1:Filters />
</q1:Drive>
<q1:Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="U:" status="U:" image="2" changed="2022-06-21 11:48:53" uid="{C52EA73F-41CF-4C08-8510-199296A53FE1}">
<q1:GPOSettingOrder>3</q1:GPOSettingOrder>
<q1:Properties action="U" thisDrive="SHOW" allDrives="NOCHANGE" userName="" path="\\192.168.0.1\%username%" label="Perso" persistent="0" useLetter="1" letter="U" />
<q1:Filters />
</q1:Drive>
</q1:DriveMapSettings>
</Extension>
<Name>Drive Maps</Name>
</ExtensionData>
</User>
<LinksTo>
<SOMName>mdv</SOMName>
<SOMPath>mdv.lan</SOMPath>
<Enabled>true</Enabled>
<NoOverride>false</NoOverride>
</LinksTo>
</GPO>';
$xmlObject = new SimpleXMLElement($xml);
$json = xmlToArray($xmlObject, array(
'namespaceRecursive' => true,
'removeNamespace' => true
));
echo json_encode($json);
EDIT : a conversion to PureBasic would be wonderfull
