You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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 walson or nelson), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:19:50