Guest User

Untitled

a guest
Mar 9th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.11 KB | None | 0 0
  1. <?php
  2. /*
  3. Написать клас или добавить методы к существующему классу для работы с csv которые реализуют следущий функционал:
  4. Выбирать данные из таблицы пользователей, генерить из них валидную XML c помощью simpleXML, создавать файл result.xml в который вставлять созданную валидную XML.
  5. Из файла XML, генерировать массив и данные из этого массива вставлять в базу данных.
  6. */
  7. class CsvXml {
  8.  
  9. private $db;
  10. private $dbHost;
  11. private $dbUser;
  12. private $dbPass;
  13. private $dbCharset;
  14. private $dbOptions;
  15. private $dbTable;
  16. private $createCsvFileName = 'user.csv';
  17. private $createXmlFileName = 'result.xml';
  18. private $workCsvFileName = 'users.csv';
  19. private $workXmlFileName = 'result.xml';
  20.  
  21. public function __construct($table) {
  22. $this->dbTable = $table;
  23. }
  24.  
  25. public function getArrFromCsv($data) {
  26. $fileOpen = fopen($this->$workCsvFileName, 'r');
  27. $arr = [];
  28. while ($fileArray = fgetcsv($fileOpen, 1000, ';')) {
  29. $arr[] = $fileArray;
  30. }
  31. fclose($fileOpen);
  32. return $arr;
  33. }
  34.  
  35. public function getCsvFile($data) {
  36. $fileOpen = fopen($this->$createCsvFileName, 'a+');
  37. foreach ($data as $value) {
  38. fwrite($fileOpen, '"' . implode($value, '";"') . PHP_EOL);
  39. }
  40. fclose($fileOpen);
  41. }
  42.  
  43. public function getXmlFile($xml = null) {
  44. if (!isset($fileXml))
  45. $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><users></users>");
  46. $data = $this->selectData();
  47. while ($arr = $data->fetch()) {
  48. $user = $xml->addChild('user');
  49. $user->addAttribute('id', $arr['id']);
  50. $newArr = [];
  51. foreach ($arr as $key => $value) {
  52. if ($key == 'id')
  53. continue;
  54. $newArr[$key] = $value;
  55. }
  56. $newArr = array_flip($newArr);
  57. array_walk($newArr, [$user, 'addChild']);
  58. }
  59. $xmlFile = $xml->asXML($this->createXmlFileName);
  60. }
  61.  
  62. public function insertXmlToDatabase($data) {
  63. if (file_exists($data)) {
  64. $xml = simplexml_load_file($data);
  65. $json = json_encode($xml);
  66. $data = json_decode($json, TRUE);
  67. foreach ($data['user'] as $item) {
  68. if ($item['@attributes']) {
  69. unset($item['@attributes']);
  70. }
  71. $fieldsProp = array_fill(0, count($item), '?');
  72. $fieldsName = array_keys($item);
  73. $fieldsVal = array_values($item);
  74. $sql = "INSERT INTO $this->dbTable( " . implode(",", $fieldsName) . " ) values( " . implode(",", $fieldsProp) . " );";
  75. $stmt = $this->connectDb()->prepare($sql);
  76. $stmt->execute($fieldsVal);
  77. }
  78. } else {
  79. die("Не удалось отурыть файл $data");
  80. }
  81. }
  82.  
  83. public function selectData() {
  84. $sql = "SELECT * FROM $this->dbTable";
  85. $query = $this->connectDb()->prepare($sql);
  86. $query->execute();
  87. return $query;
  88. }
  89.  
  90. private function connectDb() {
  91. $dsn = "mysql:host=$this->dbHost;dbname=$this->db;charset=$this->dbCharset";
  92. $pdo = new PDO($dsn, $this->dbUser, $this->dbPass, $this->dbOptions);
  93. return $pdo;
  94. }
  95.  
  96. public function insertCsvToDatabase($data) {
  97. foreach ($data as $arr) {
  98. $newArr = [];
  99. for ($i = 1; $i < count($arr) - 2; $i++) {
  100. $elem = $arr[$i];
  101. if (is_numeric($elem)) {
  102. $newArr[] = (int) $elem;
  103. } else {
  104. $newArr[] = $elem;
  105. }
  106. }
  107. $sql = "INSERT INTO $this->dbTable(`nick_name`,`user_name`,`age`,`surname`,`email`,`password`,`date_of_birth`) VALUES(?,?,?,?,?,?,?)";
  108. $query = $this->connectDb()->prepare($sql);
  109. $query->execute($newArr);
  110. }
  111. }
  112.  
  113. public function uploadingData($fields, $where = '') {
  114. $sql = "SELECT $fields FROM $this->dbTable $where";
  115. $query = $this->connectDb()->prepare($sql);
  116. $query->execute();
  117. $sth = $query->fetchAll();
  118. $this->getArrFromCsv($sth);
  119. }
  120.  
  121. public function setConfig($host, $db, $user, $pass, $charset, $options) {
  122. $this->dbHost = $host;
  123. $this->db = $db;
  124. $this->dbUser = $user;
  125. $this->dbPass = $pass;
  126. $this->dbCharset = $charset;
  127. $this->dbOptions = $options;
  128. }
  129.  
  130. private function cleanData($value) {
  131. $value = trim($value);
  132. $value = strip_tags($value);
  133. $value = stripcslashes($value);
  134. return $value;
  135. }
  136.  
  137. }
  138.  
  139. $csv = new CsvXml('users');
  140. $csv->setConfig('127.0.0.1', 'file', 'root', '', 'utf8', [
  141. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  142. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
  143. ]);
  144.  
  145. //$csv->getXmlFile();
  146. //$csv->insertXmlToDatabase('result.xml');
Add Comment
Please, Sign In to add comment