PHP - XML - Exporting Data to XML

Turn the result set into an XML document with PHP's DOM functions:

 

  1. <?php
  2. // open connection
  3. $mysqli = new mysqli("localhost""user""pass""db1");
  4. if (mysqli_connect_errno()) {
  5.     die("ERROR: Cannot connect. " . mysqli_connect_error());
  6. }
  7. // create and execute SELECT query
  8. $sql = "SELECT id, name, price FROM products";
  9. if ($result = $mysqli->query($sql)) {
  10.     // if results exist
  11.     // initialize DOM object
  12.     $xml = new DOMDocument("1.0");
  13.     // add root node
  14.     $root = $xml->createElement("resultset");
  15.     $xml->appendChild($root);
  16.     // iterate over result set
  17.     // print <record>s and <field>s
  18.     if ($result->num_rows > 0) {
  19.         while($row = $result->fetch_row()) {
  20.             $record = $xml->createElement("record");
  21.             $root->appendChild($record);
  22.             $fieldCount = 0;
  23.             while ($fieldCount < $mysqli->field_count) {
  24.                 $field = $xml->createElement("field");
  25.                 $record->appendChild($field);
  26.                 $field->appendChild(↩
  27. $xml->createTextNode($row[$fieldCount]));
  28.                    $fieldCount++;
  29.                }
  30.            }
  31.     }
  32.     $result->close();
  33. else {
  34.     die("ERROR: " . $mysqli->error . " (query was $sql)");
  35. }
  36. // close connection
  37. $mysqli->close();
  38. // display XML result set as HTML…
  39. $xml->formatOutput = true;
  40. echo "<xmp>" . $xml->saveXML() . "</xmp>";
  41. // …or write it to a file as XML
  42. $xml->save("results.xml"or die("ERROR: Could not write to file");
  43. ?>

Comments

There are a number of reasons why you might want to export a SQL result set to an XML file: to make the data more usable and portable, to reduce your application's dependence on a database server, or to improve performance (because it's usually faster to read from a disk file than from a network connection).

The previous listing shows you how, by executing a SELECT query and then converting the resulting data set into a series of <record> and <field> elements. PHP's DOM extension, which comes with built-in support for dynamically adding nodes to an XML document tree, takes care of the heavy lifting with its createElement(), createTextNode(), and appendChild() methods (these methods are discussed in greater detail in the listings in "10.4: Creating XML" and "10.5: Adding or Removing XML Nodes"). Once the document has been completely generated, it may be written to a file via the save() method, or returned as a string suitable for display with the saveXML() method.

You can also do the reverse: read data from an XML file and write it to a database. The next listing demonstrates this, using SimpleXML to parse an XML file and generate a series of SQL INSERT statements from it:

 

  1. <?php
  2. $xmlData =<<< END
  3. <?xml version="1.0"?>
  4. <data>
  5.      <item>
  6.           <id>20</id>
  7.           <name>mangoes</name>
  8.           <price>11</price>
  9.      </item>
  10.      <item>
  11.           <id>22</id>
  12.           <name>strawberries</name>
  13.           <price>5</price>
  14.       </item>
  15.       <item>
  16.            <id>23</id>
  17.            <name>grapes</name>
  18.            <price>25</price>
  19.        </item>
  20.    </data>
  21. END;
  22. // read XML data string
  23. $xml = simplexml_load_string($xmlData)↩
  24. or die("ERROR: Cannot create SimpleXML object");
  25. // open MySQL connection
  26. $connection = mysqli_connect("localhost""user""pass""db1")↩
  27. or die ("ERROR: Cannot connect");
  28. // process node data
  29. // create and execute INSERT queries
  30. foreach ($xml->item as $item) {
  31.     $id = $item->id;
  32.     $name = mysqli_real_escape_string($connection$item->name);
  33.     $price = $item->price;
  34.     $sql = "INSERT INTO products (id, name, price)↩
  35. VALUES ('$id''$name''$price')";
  36.     mysqli_query($connection$sqlor die ("ERROR: " .↩
  37. mysqli_error($connection) . " (query was $sql)");
  38. }
  39. // close connection
  40. mysqli_close($connection);
  41. ?>

In this listing, SimpleXML is used to iterate over each <item> in the XML document and generate an SQL INSERT statement from the values contained within it. PHP's ext/mysqli functions are then used to execute each INSERT statement on the database server, thus writing the data to the database.

Tip 

Metabase is a PHP-based database abstraction layer that uses XML to express table relationships, structures and records. Read more about it at http://www.phpclasses.org/metabase.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值