<th width="10%">calories</th>
</tr>
<?php
// 使用 simpleXML 处理 XML
$xml = simplexml_load_file('./simple.xml');
//var_dump($xml);
//echo $xml->getName();
//var_dump($xml->children());
$record = '';
foreach ($xml->children() as $child)
{
$record .= '<tr><td>'. $child->attributes(). '</td>';
foreach ($child->children() as $item)
{
//var_dump($child);
$record .= '<td>'. $item .'</td>';
}
$record .= '</tr>';
}
echo $record;
?>
</tbody>
</table>
</body>
</html>
将
XML 转换为数组结构
代码如下
private function change_simple_xml_to_array($obj){
$i = 0;
//从根节点下的二层子节点开始遍历
foreach($obj->children() as $value){
//如果发生同级、同标签名的情况,则加一维数组;
if(isset($last_name) && $value->getName()==$last_name){
//出现同名发现第二个,则推入第二维数组;
if($i==1) $arr[$last_name]=array($arr[$last_name]);
//遍历子节点;
array_push($arr[$last_name],$this->change_simple_xml_to_array($value));
}else{
$last_name = $value->getName();
if(count($value->children())==0) $arr[$last_name] = $value."";
else $arr[$last_name] = $this->change_simple_xml_to_array($value);
}
$i++;
}