Home >Backend Development >PHP Tutorial >How to interact with database and store in XML format in PHP
How to interact with the database in PHP and store it in XML format
In web applications, interacting with the database is a very common and important operation. Storing data obtained from the database in XML format is a convenient way to exchange data between different platforms and different languages. This article will introduce how to interact with the database in PHP and store the data in XML format.
First, we need to establish a database connection. In PHP, you can use mysqli or PDO extensions to interact with the database. In this example we will use the mysqli extension.
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; // 建立与数据库的连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
Next, we need to execute the SQL query statement to obtain the data in the database. In this example, we will get all the data from a table called "users".
$sql = "SELECT * FROM users"; $result = $conn->query($sql);
Then, we need to convert the query results into XML format. In PHP, you can use the SimpleXMLElement class to create and manipulate XML documents.
$xml = new SimpleXMLElement('<users></users>'); while($row = $result->fetch_assoc()) { $user = $xml->addChild('user'); $user->addChild('id', $row['id']); $user->addChild('name', $row['name']); $user->addChild('email', $row['email']); }
In the above code, we use the addChild method to add elements and data to the XML document.
Finally, we need to save the XML document to a file. In this example we will save it as users.xml.
$xml->asXML('users.xml');
The complete code example is as follows:
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; // 建立与数据库的连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 执行SQL查询语句 $sql = "SELECT * FROM users"; $result = $conn->query($sql); // 创建XML文档 $xml = new SimpleXMLElement(''); // 将查询结果转换为XML格式 while($row = $result->fetch_assoc()) { $user = $xml->addChild('user'); $user->addChild('id', $row['id']); $user->addChild('name', $row['name']); $user->addChild('email', $row['email']); } // 保存XML文档 $xml->asXML('users.xml');
The above code implements the function of storing data obtained from the database in XML format. You can change the structure of SQL query statements and XML elements according to your needs. At the same time, you can also use other PHP extensions or libraries to achieve similar functions, such as using the DOMDocument class to build and manipulate XML documents.
The above is the detailed content of How to interact with database and store in XML format in PHP. For more information, please follow other related articles on the PHP Chinese website!