Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Написать клас или добавить методы к существующему классу для работы с csv которые реализуют следущий функционал:
- Выбирать данные из таблицы пользователей, генерить из них валидную XML c помощью simpleXML, создавать файл result.xml в который вставлять созданную валидную XML.
- Из файла XML, генерировать массив и данные из этого массива вставлять в базу данных.
- */
- class CsvXml {
- private $db;
- private $dbHost;
- private $dbUser;
- private $dbPass;
- private $dbCharset;
- private $dbOptions;
- private $dbTable;
- private $createCsvFileName = 'user.csv';
- private $createXmlFileName = 'result.xml';
- private $workCsvFileName = 'users.csv';
- private $workXmlFileName = 'result.xml';
- public function __construct($table) {
- $this->dbTable = $table;
- }
- public function getArrFromCsv($data) {
- $fileOpen = fopen($this->$workCsvFileName, 'r');
- $arr = [];
- while ($fileArray = fgetcsv($fileOpen, 1000, ';')) {
- $arr[] = $fileArray;
- }
- fclose($fileOpen);
- return $arr;
- }
- public function getCsvFile($data) {
- $fileOpen = fopen($this->$createCsvFileName, 'a+');
- foreach ($data as $value) {
- fwrite($fileOpen, '"' . implode($value, '";"') . PHP_EOL);
- }
- fclose($fileOpen);
- }
- public function getXmlFile($xml = null) {
- if (!isset($fileXml))
- $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><users></users>");
- $data = $this->selectData();
- while ($arr = $data->fetch()) {
- $user = $xml->addChild('user');
- $user->addAttribute('id', $arr['id']);
- $newArr = [];
- foreach ($arr as $key => $value) {
- if ($key == 'id')
- continue;
- $newArr[$key] = $value;
- }
- $newArr = array_flip($newArr);
- array_walk($newArr, [$user, 'addChild']);
- }
- $xmlFile = $xml->asXML($this->createXmlFileName);
- }
- public function insertXmlToDatabase($data) {
- if (file_exists($data)) {
- $xml = simplexml_load_file($data);
- $json = json_encode($xml);
- $data = json_decode($json, TRUE);
- foreach ($data['user'] as $item) {
- if ($item['@attributes']) {
- unset($item['@attributes']);
- }
- $fieldsProp = array_fill(0, count($item), '?');
- $fieldsName = array_keys($item);
- $fieldsVal = array_values($item);
- $sql = "INSERT INTO $this->dbTable( " . implode(",", $fieldsName) . " ) values( " . implode(",", $fieldsProp) . " );";
- $stmt = $this->connectDb()->prepare($sql);
- $stmt->execute($fieldsVal);
- }
- } else {
- die("Не удалось отурыть файл $data");
- }
- }
- public function selectData() {
- $sql = "SELECT * FROM $this->dbTable";
- $query = $this->connectDb()->prepare($sql);
- $query->execute();
- return $query;
- }
- private function connectDb() {
- $dsn = "mysql:host=$this->dbHost;dbname=$this->db;charset=$this->dbCharset";
- $pdo = new PDO($dsn, $this->dbUser, $this->dbPass, $this->dbOptions);
- return $pdo;
- }
- public function insertCsvToDatabase($data) {
- foreach ($data as $arr) {
- $newArr = [];
- for ($i = 1; $i < count($arr) - 2; $i++) {
- $elem = $arr[$i];
- if (is_numeric($elem)) {
- $newArr[] = (int) $elem;
- } else {
- $newArr[] = $elem;
- }
- }
- $sql = "INSERT INTO $this->dbTable(`nick_name`,`user_name`,`age`,`surname`,`email`,`password`,`date_of_birth`) VALUES(?,?,?,?,?,?,?)";
- $query = $this->connectDb()->prepare($sql);
- $query->execute($newArr);
- }
- }
- public function uploadingData($fields, $where = '') {
- $sql = "SELECT $fields FROM $this->dbTable $where";
- $query = $this->connectDb()->prepare($sql);
- $query->execute();
- $sth = $query->fetchAll();
- $this->getArrFromCsv($sth);
- }
- public function setConfig($host, $db, $user, $pass, $charset, $options) {
- $this->dbHost = $host;
- $this->db = $db;
- $this->dbUser = $user;
- $this->dbPass = $pass;
- $this->dbCharset = $charset;
- $this->dbOptions = $options;
- }
- private function cleanData($value) {
- $value = trim($value);
- $value = strip_tags($value);
- $value = stripcslashes($value);
- return $value;
- }
- }
- $csv = new CsvXml('users');
- $csv->setConfig('127.0.0.1', 'file', 'root', '', 'utf8', [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
- ]);
- //$csv->getXmlFile();
- //$csv->insertXmlToDatabase('result.xml');
Add Comment
Please, Sign In to add comment