PHP中如何将XML转换为指定嵌套结构的数组?
Fixing XML to PHP Array Conversion: Match Your Desired Structure
Hey there! Let's sort out this XML-to-array conversion issue you're facing. The problem with your current code is that simplexml_load_file() returns a SimpleXMLElement object, not a plain PHP array. We need to convert this object into the nested array format you specified. Here are two reliable solutions:
Method 1: Quick Conversion with JSON Encode/Decode
This is a fast, low-effort way to get your target array, with a quick cleanup step to fix the extra > in your XML's <a> elements:
$file = "product.xml"; $xml = simplexml_load_file($file) or die("ERROR loading file"); // Convert the SimpleXMLElement object to a raw array $rawArray = json_decode(json_encode($xml), true); // Extract the article data and format it to match your desired structure $testArray = $rawArray['article']; // Clean up the trailing ">" in the <a> values (matches your expected output) foreach ($testArray as &$item) { $item['a'] = rtrim($item['a'], '>'); } // Verify the result print_r($testArray);
This will output exactly the array you want:
Array ( [0] => Array ( [a] => TEST [b] => TEST2 [c] => TEST3 ) [1] => Array ( [a] => TEST4 [b] => TEST5 [c] => TEST6 ) )
Method 2: Manual Traversal (Full Control)
If you want more control over the conversion (e.g., handling edge cases or custom transformations), loop through each <article> element manually:
$file = "product.xml"; $xml = simplexml_load_file($file) or die("ERROR loading file"); $testArray = []; foreach ($xml->article as $article) { $testArray[] = [ 'a' => rtrim((string)$article->a, '>'), // Cast to string + clean up 'b' => (string)$article->b, 'c' => (string)$article->c ]; } // Verify the result print_r($testArray);
Key Details to Remember:
- Casting to String: When accessing SimpleXMLElement properties (like
$article->a), always cast to a string with(string)—this pulls out the actual text content instead of returning an object. - Special Character Cleanup: Your XML includes
TEST>andTEST4>in the<a>tags. Thertrim()call removes the trailing>to match your expected output. If this was a typo in your XML, you could fix the source file instead, but the code handles it either way.
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

