Как загрузить данные XML в MySQL с помощью PHP?
В этой статье мы собираемся хранить данные, представленные в файле XML, в базе данных MySQL, используя PHP на сервере XAMPP.
XML: Extensible Markup Language (XML) - это язык разметки, который определяет набор правил для кодирования документов в формате, который удобен для чтения человеком и компьютером. Цели разработки XML сосредоточены на простоте, универсальности и удобстве использования в Интернете.
Example:
HTML
<? xml version = "1.0" encoding = "UTF-8" ?> < datas > < data > < id >1</ id > < name >sravan</ name > </ data > < data > < id >2</ id > < name >Ojaswi</ name > </ data > < data > < id >3</ id > < name >Rohith</ name > </ data > </ datas > |
Загрузка XML-файла: мы будем использовать функцию simplexml_load_file () для преобразования правильно сформированного XML-документа из заданного файла в объект.
Синтаксис:
SimpleXMLElement simplexml_load_file ( строка $ filename, строка $ class_name = "SimpleXMLElement", int $ options = 0, строка $ ns = "", bool $ is_prefix = FALSE)
Шаги по написанию и выполнению кода:
- Запустить XAMPP
- Определите количество атрибутов в XML-файле и создайте таблицу в XAMPP. В XML-файле есть 4 атрибута (input.xml - это имя файла). Это заголовок, ссылка. описание, ключевые слова. Имя базы данных - xmldata, имя таблицы - xml.
Filename: input.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?> < items > < item > < title >PHP DATABASE CONNECTION</ title > < link > </ link > < description > The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. </ description > < keywords >PHP, XAMPP</ keywords > </ item > < item > < title >Screen density and Terminologies</ title > < link > </ link > < description > Screen Density is a calculation of the proportion of display character positions on the screen or an area of the screen containing something. </ description > < keywords >software engineering</ keywords > </ item > < item > < title >DataProcessing vs DataCleaning</ title > < link > </ link > < description > Data Processing: It is defined as Collection, manipulation, and processing of collected data for the required use. It is a task of converting data from a given form to a much more usable and desired form i.e. making it more meaningful and informative. Using Machine Learning algorithms, mathematical modelling and statistical knowledge, this entire process can be automated. This might seem to be simple but when it comes to really big organizations like Twitter, Facebook, Administrative bodies like Paliament, UNESCO and health sector </ description > < keywords >Data Mining</ keywords > </ item > < item > < title >Predicting Air Quality Index</ title > < link > </ link > < description > AQI: The air quality index is an index for reporting air quality on a daily basis. In other words, it is a measure of how air pollution affects one’s health within a short time period. The AQI is calculated based on the average concentration of a particular pollutant measured over a standard time interval. Generally, the time interval is 24 hours for most pollutants, 8 hours for carbon monoxide and ozone. </ description > < keywords >Machine Learning, Python</ keywords > </ item > </ items > |
Filename: index.php
PHP
<?php // Connect to database // Server - localhost // Username - root // Password - empty // Database name = xmldata $conn = mysqli_connect( "localhost" , "root" , "" , "xmldata" ); $affectedRow = 0; // Load xml file else check connection $xml = simplexml_load_file( "input.xml" ) or die ( "Error: Cannot create object" ); // Assign values foreach ( $xml ->children() as $row ) { $title = $row ->title; $link = $row ->link; $description = $row ->description; $keywords = $row ->keywords; // SQL query to insert data into xml table $sql = "INSERT INTO xml(title, link, description, keywords) VALUES ("" . $title . "","" . $link . "","" . $description . "","" . $keywords . "")" ; $result = mysqli_query( $conn , $sql ); if (! empty ( $result )) { $affectedRow ++; } else { $error_message = mysqli_error( $conn ) . "
" ; } } ?> <center><h2>GEEKS GOR GEEKS</h2></center> <center><h1>XML Data storing in Database</h1></center> <?php if ( $affectedRow > 0) { $message = $affectedRow . " records inserted" ; } else { $message = "No records inserted" ; } ?> <style> body { max-width:550px; font-family: Arial; } .affected-row { background: #cae4ca; padding: 10px; margin-bottom: 20px; border: #bdd6bd 1px solid; border-radius: 2px; color: #6e716e; } .error-message { background: #eac0c0; padding: 10px; margin-bottom: 20px; border: #dab2b2 1px solid; border-radius: 2px; color: #5d5b5b; } </style> <div class = "affected-row" > <?php echo $message ; ?> </div> <?php if (! empty ( $error_message )) { ?> <div class = "error-message" > <?php echo nl2br ( $error_message ); ?> </div> <?php } ?> |
Шаги выполнения:
1. Сохраните 2 файла в одной папке по пути: xampp / htdocs / gfg.
2. Введите localhost / gfg / index.php и просмотрите результат.

выход
Теперь проверьте данные в xml, хранящиеся в нашей базе, или нет