Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chuyển file XML thành mảng trong PHP

Quy trình 5 bước:

  1. Tạo file XML (ví dụ abc.xml).
  2. Đọc toàn bộ file thành chuỗi bằng file_get_contents().
  3. Chuyển chuỗi XML thành object SimpleXMLElement bằng simplexml_load_string().
  4. Encode object thành JSON bằng json_encode().
  5. 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.