Quy trình 5 bước:
- Tạo file XML (ví dụ
abc.xml). - Đọc toàn bộ file thành chuỗi bằng
file_get_contents(). - Chuyển chuỗi XML thành object
SimpleXMLElementbằngsimplexml_load_string(). - Encode object thành JSON bằng
json_encode(). - Decode JSON thành mảng PHP bằng
json_decode($json, true).
Ví dụ
<?php
$path = "abc.xml";
$xmlStr = file_get_contents($path);
$xmlObj = simplexml_load_string($xmlStr);
$json = json_encode($xmlObj);
$array = json_decode($json, true);
print_r($array);
?>
Lưu ý: Cách này chuyển attribute XML thành property object, có thể mất thứ tự hoặc cấu trúc phức tạp. Với XML phức tạp, cân nhắc dùng DOMDocument hoặc thư viện chuyên biệt.