PHP'de XML Diziye Nasıl Dönüştürülür?

27 Haziran 2023 175 Okuma süresi: 1 dakika

Bazı API`lerin response değerleri xml formatında oluyor ve ya ürün listesi gibi verileri işlemek durumuyla karşı karşıya kaliyoruz.

Peki PHP ile xml (SimpleXMLElement) formatı nasıl array formatına çevire biliriz.

Aşağıdakı php fonksionunu kullanarak SimpleXMLElement ile aldığınız değeri normal Array formatına çevire bilirsiniz.

function xmlToArray(SimpleXMLElement $xml): array {
    $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
    $nodes = $xml->children();
    $attributes = $xml->attributes();
    if (0 !== count($attributes)) {
        foreach ($attributes as $attrName => $attrValue) {
            $collection['attributes'][$attrName] = strval($attrValue);
        }
    }
    if (0 === $nodes->count()) {
        $collection['value'] = strval($xml);
        return $collection;
    }
    foreach ($nodes as $nodeName => $nodeValue) {
        if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
            $collection[$nodeName] = $parser($nodeValue);
            continue;
        }
        $collection[$nodeName][] = $parser($nodeValue);
    }
    return $collection;
};
return [ $xml->getName() => $parser($xml)];
}

Benzer makaleler