将 XML 插入数据库
如果要将 XML 保存到数据库中,请将 '$xml_file' 变量行替换为以下代码行。
现在我们可以将 '$xml_file' 变量插入到数据库中。
$xml_file = $xml_user_info->asXML();
PHP将数组转换为 XML文件:
现在我们将使用 PHP 'SimpleXML' 将用户数组转换为 XML。
请按照注释标签更好地理解。
//function defination to convert array to xml function array_to_xml($array, &$xml_user_info) { foreach($array as $key => $value) { if(is_array($value)) { if(!is_numeric($key)){ $subnode = $xml_user_info->addChild("$key"); array_to_xml($value, $subnode); }else{ $subnode = $xml_user_info->addChild("item$key"); array_to_xml($value, $subnode); } }else { $xml_user_info->addChild("$key",htmlspecialchars("$value")); } } } //creating object of SimpleXMLElement $xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user_info></user_info>"); //function call to convert array to xml array_to_xml($users_array,$xml_user_info); //saving generated xml file $xml_file = $xml_user_info->asXML('users.xml'); //success and error message based on xml creation if($xml_file){ echo 'XML file have been generated successfully.'; }else{ echo 'XML file generation error.'; }
XML文件:
“users.xml”文件包含以下 xml。
<?xml version="1.0"?> <user_info> <total_users>3</total_users> <users> <item0> <id>1</id> <name>Smith</name> <address> <country>United Kingdom</country> <city>London</city> <zip>56789</zip> </address> </item0> <item1> <id>2</id> <name>John</name> <address> <country>USA</country> <city>Newyork</city> <zip>NY1234</zip> </address> </item1> <item2> <id>3</id> <name>Viktor</name> <address> <country>Australia</country> <city>Sydney</city> <zip>123456</zip> </address> </item2> </users> </user_info>
很多时候我们需要将数据作为 XML 存储到数据库或者文件中以备后用。
为了满足这一需求,我们需要将数据转换为 XML 并保存 XML 文件。
在本教程中,我们将讨论如何在 PHP 中从数组创建 XML。
我们已经创建了一个简单的脚本来将 PHP 数组转换为 XML。
我们可以轻松地从 PHP 数组生成 XML 文件并保存该 XML 文件。
我们可以转换所有类型的数组,如关联数组或者多维数组。
PHP数组:
首先,我们将用户数据存储到一个变量( '$users_array' )中。
$users_array = array( "total_users" => 3, "users" => array( array( "id" => 1, "name" => "Smith", "address" => array( "country" => "United Kingdom", "city" => "London", "zip" => 56789, ) ), array( "id" => 2, "name" => "John", "address" => array( "country" => "USA", "city" => "Newyork", "zip" => "NY1234", ) ), array( "id" => 3, "name" => "Viktor", "address" => array( "country" => "Australia", "city" => "Sydney", "zip" => 123456, ) ), ) );
日期:2020-06-02 22:15:26 来源:oir作者:oir