在 PHP 中,将数组转换为 SimpleXML 对象可以是操作 XML 数据的便捷方法。
以下代码片段提供了将数组转换为 SimpleXML 问题的解决方案object:
// Array to be converted $data = array( 'total_stud' => 500, 0 => array( 'student' => array( 'id' => 1, 'name' => 'abc', 'address' => array( 'city' => 'Pune', 'zip' => 411006 ) ) ), 1 => array( 'student' => array( 'id' => 2, 'name' => 'xyz', 'address' => array( 'city' => 'Mumbai', 'zip' => 400906 ) ) ) ); // Create a SimpleXMLElement object $xml_data = new SimpleXMLElement('<?xml version="1.0"?><student_info></student_info>'); // Function to convert array to XML function array_to_xml($data, &$xml_data) { foreach ($data as $key => $value) { if (is_array($value)) { if (is_numeric($key)) { $key = 'item' . $key; // Handle numeric keys } $subnode = $xml_data->addChild($key); array_to_xml($value, $subnode); } else { $xml_data->addChild("$key", htmlspecialchars("$value")); } } } // Convert array to XML array_to_xml($data, $xml_data); // Save the generated XML file $result = $xml_data->asXML('/file/path/name.xml');
此代码定义了一个名为 array_to_xml 的函数,该函数递归地迭代数组并将 SimpleXMLElement 节点添加到提供的 $xml_data 对象中。它通过添加 item 前缀来处理数字数组键。 htmlspecialchars 函数用于转义数组值中的任何特殊字符,以确保正确的 XML 格式。最后,生成的 XML 使用 asXML 保存到文件中。
以上是如何将 PHP 数组转换为 SimpleXML 对象?的详细内容。更多信息请关注PHP中文网其他相关文章!