如何从SimpleXMLElement对象数组提取键值并格式化输出(PHP)
Hey there! Let's walk through how to generate that exact formatted string from your SimpleXMLElement structure in PHP.
Solution Code
First, let's assume your original XML object is stored in a variable called $xmlObj. Here's a clean, readable approach to get the output you want:
// Your original SimpleXMLElement Object $xmlObj = ...; // Replace with your actual object $formattedSegments = []; // Iterate over each item with its index foreach ($xmlObj->items as $index => $item) { // Collect each name-value pair as a string $itemDetails = []; foreach ($item as $name => $value) { $itemDetails[] = "$name $value"; } // Build the line for this index: "index, name1 val1, name2 val2..." $segment = "$index, " . implode(", ", $itemDetails); $formattedSegments[] = $segment; } // Combine all segments into the final output string $finalOutput = implode(" ", $formattedSegments); // Output the result echo $finalOutput;
How This Works
- Loop through items: Using
foreach ($xmlObj->items as $index => $item)lets us grab both the position (0, 1, 2) and the corresponding child object for each entry. - Process each item: For every child element in the item (like
walsonornelson), we create a string like"walson 986"and add it to an array. - Build index-specific lines: We join those name-value strings with
", ", then prepend the index to make a line like"0, walson 986, john 01, merry 234". - Combine everything: Finally, we join all those index lines with a space to get the full formatted string you need.
When you run this with your provided structure, you'll get exactly the output you're looking for:
0, walson 986, john 01, merry 234 1, nelson 987, richard 01, joan 345 2, danny 989, soffie 02, roland 345
内容的提问来源于stack exchange,提问作者AWinx
相关产品推荐
相关产品推荐

