Ejemplo n.º 1
0
function xmlToArray($xmlstring)
{
    // fix the xml if it's invalid
    $origstring = $xmlstring;
    $xmlstring = stripInvalidUtf8Chars($xmlstring);
    $xmlstring = stripXMLInvalidChars($xmlstring);
    $xmlstring = str_replace('&', '&', $xmlstring);
    $xmlstring = str_replace(array('&#', '<', '>', '"', '&', '''), array('&#', '<', '>', '"', '&', '''), $xmlstring);
    if ($xmlstring != $origstring) {
        //printStringDiff($xmlstring, $origstring);
        //return null;
    }
    // strip any namespaces from the xml
    $matches = null;
    if (preg_match_all('/<([\\w]+):/', $xmlstring, $matches)) {
        $namespaces = array_unique($matches[1]);
        foreach ($namespaces as $namespace) {
            $xmlstring = str_replace("<{$namespace}:", "<{$namespace}_", $xmlstring);
            $xmlstring = str_replace("</{$namespace}:", "</{$namespace}_", $xmlstring);
        }
    }
    // parse the xml
    $xml = @simplexml_load_string($xmlstring);
    $json = json_encode($xml);
    $array = json_decode($json, TRUE);
    if (!$array) {
        // failed to parse as XML try JSON (for feeds)
        $xmlstring = preg_replace('/,\\s*\\]/', ']', $xmlstring);
        $xmlstring = preg_replace('/,\\s*\\}/', '}', $xmlstring);
        $array = json_decode($xmlstring, TRUE);
        if ($array) {
            echo "\nSuccessfully parsed as json";
        }
    }
    return $array;
}
Ejemplo n.º 2
0
function xmlToArray($xmlstring)
{
    // fix the xml if it's invalid
    $origstring = $xmlstring;
    $xmlstring = stripInvalidUtf8Chars($xmlstring);
    $xmlstring = stripXMLInvalidChars($xmlstring);
    $xmlstring = str_replace('&', '&amp;', $xmlstring);
    $xmlstring = str_replace(array('&amp;#', '&amp;lt;', '&amp;gt;', '&amp;quot;', '&amp;amp;', '&amp;apos;'), array('&#', '&lt;', '&gt;', '&quot;', '&amp;', '&apos;'), $xmlstring);
    if ($xmlstring != $origstring) {
        //printStringDiff($xmlstring, $origstring);
        //return null;
    }
    // parse the xml
    $xml = @simplexml_load_string($xmlstring);
    $json = json_encode($xml);
    $array = json_decode($json, TRUE);
    if (!$array) {
        // failed to parse as XML try JSON (for feeds)
        $xmlstring = preg_replace('/,\\s*\\]/', ']', $xmlstring);
        $xmlstring = preg_replace('/,\\s*\\}/', '}', $xmlstring);
        $array = json_decode($xmlstring, TRUE);
        if ($array) {
            echo "\nSuccessfully parsed as json";
        }
    }
    return $array;
}