Advertisement
Guest User

Untitled

a guest
Mar 16th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <!--
  3. To change this license header, choose License Headers in Project Properties.
  4. To change this template file, choose Tools | Templates
  5. and open the template in the editor.
  6. -->
  7. <html>
  8. <head>
  9. <meta charset="UTF-8">
  10. <title></title>
  11. </head>
  12. <body>
  13. <?php
  14. // put your code here
  15. $servername = "localhost";
  16. $username = "root";
  17. $password = "";
  18. $database = "exercici4";
  19.  
  20. // Create connection
  21. $conn = new mysqli($servername, $username, $password, $database);
  22.  
  23. // Check connection
  24. if ($conn->connect_error) {
  25. die("Connection failed: " . $conn->connect_error);
  26. }
  27. echo "Connected successfully";
  28. echo "<br>";
  29.  
  30. // Store XML
  31. $xml = simplexml_load_file("menu.xml");
  32. foreach ($xml->menjar as $val) {
  33. $sql = "INSERT INTO apartatb VALUES ('$val->nom', '$val->preu', '$val->categoria', '$val->descripcio', $val->calories)";
  34.  
  35. if ($conn->query($sql) === TRUE) {
  36. echo "New record created successfully";
  37. } else {
  38. echo "Error: " . $sql . "<br>" . $conn->error;
  39. }
  40. echo "<br>";
  41. }
  42.  
  43. // Load XML
  44. $sql = "SELECT * FROM apartatb";
  45. $result = $conn->query($sql);
  46.  
  47. echo sqlToXml($result, "menu", "menjar");
  48.  
  49. function sqlToXml($queryResult, $rootElementName, $childElementName) {
  50. $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
  51. $xmlData .= "<" . $rootElementName . "> \n";
  52.  
  53. while ($record = mysqli_fetch_object($queryResult)) {
  54. /* Create the first child element */
  55. $xmlData .= "\t <" . $childElementName . "> \n";
  56.  
  57. for ($i = 0; $i < mysqli_num_fields($queryResult); $i++) {
  58. $fieldName = mysqli_fetch_field_direct($queryResult, $i)->name;
  59.  
  60. /* The child will take the name of the table column */
  61. $xmlData .= "\t\t <" . $fieldName . ">";
  62.  
  63. /* We set empty columns with NULL, or you could set
  64. it to '0' or a blank. */
  65. if (!empty($record->$fieldName)) {
  66. $xmlData .= $record->$fieldName;
  67. } else {
  68. $xmlData .= "null";
  69. }
  70. $xmlData .= "</" . $fieldName . "> \n";
  71. }
  72. $xmlData .= "\t</" . $childElementName . "> \n";
  73. }
  74. $xmlData .= "</" . $rootElementName . "> \n";
  75.  
  76. return $xmlData;
  77. }
  78. ?>
  79. </body>
  80. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement