Wednesday, January 1, 2014

How to read XML file in PHP

How to read XML file in PHP?

This article explains you how to read XML file in PHP
Read xml file in PHP

Usage of XML Documents

XML stands for Extensible Markup Language. XML files can be use to transfer and store data. XML files are both human and machine readable. XML data is stored in plain text format. Also XML documents are platform independent. XML tags are not predefined. You can use your custom tags to form a XML document. So it is very easy to create XML file for your requirement. RRS feeds and Web Services use XML for data transfer. Some applications store there configurations in XML files. For a example ASP.Net web.config file is an XML document. Both web applications and desktop applications use XML for transfer and store data. There can be small XML files and very large files up to several Gigabytes.

Download source code for read XML file

Reading XML file using PHP.

In most case you may need to read XML files. Suppose that you have to fetch product catalogue into database. All product details are provided using an XML file. Bellow example will show how to read simple XML file using PHP.

1.) How to read product catalogue XML in PHP.

Before you start reading XML file, please download the file here. Bellow example depends on the above XML file. That file contains sample product catalogue with three products. In this example I have used HTML table to view the products in the XML file.

  <?php
date_default_timezone_set("Asia/Colombo"); error_reporting(-1);//Display All errors and warnings

$xml_file_path = "products.xml"; $elements = array('id','name','category','manufacture','available');//XML nodes

if(file_exists($xml_file_path)){ echo '<table border=\'1\'><tr>'; foreach($elements as $th){ echo '<th>'.ucfirst($th).'</th>'; }
echo '</tr>';
$xml_doc = new DOMDocument();
$xml_doc->load($xml_file_path);

$products = $xml_doc->getElementsByTagName("product"); $total_products = $products->length;

foreach ($products as $product){
echo '<tr>';
foreach($elements as $element){ echo '<td>'.getNodeValue($product,$element).'</td>'; } echo '</tr>'; } echo '</table>'; echo '<p>'.$total_products.' products in the XML file</p>'; }else{ exit("XML file does not exists"); }

function getNodeValue(&$DOMElement,$nodeName){ if($DOMElement->getElementsByTagName($nodeName)->length==1){ return $DOMElement->getElementsByTagName($nodeName)->item(0)->nodeValue; }else{ return NULL; } }
?>

2.) Read XML file and insert data to MySQL database using PHP.

Sometimes you may need to insert data in a XML file in to database table. In this example I will explain you how to read XML file and insert data in to the database using our products.xml file. First of all you have to create a table to store products.

Table Structure

  CREATE TABLE `product` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`category` varchar(100) DEFAULT NULL,
`manufacture` varchar(255) DEFAULT NULL,
`qty` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
PHP code to import data:

  <?php
date_default_timezone_set("Asia/Colombo"); error_reporting(-1);

$xml_file_path = "products.xml";

if(file_exists($xml_file_path)){
$dbCon = new mysqli('localhost', 'root', '1234', 'test', 3306);//Database Connection $xml_doc = new DOMDocument(); $xml_doc->load($xml_file_path);

$products = $xml_doc->getElementsByTagName("product"); $insertCount = 0;

foreach ($products as $product){
$sql="INSERT INTO product(" . "name," . "category," . "manufacture," . "qty" . ")" . "VALUES(" . "'".$dbCon->escape_string(getNodeValue($product,'name'))."'," . "'".$dbCon->escape_string(getNodeValue($product,'category'))."'," . "'".$dbCon->escape_string(getNodeValue($product,'manufacture'))."'," . "".(int)getNodeValue($product,'available')."" . ")";
$dbCon->query($sql); $insertCount++; }
$dbCon->close(); echo '<p>'.$insertCount.' products fetched in to the database</p>'; }else{ exit("XML file does not exists"); }

function getNodeValue(&$DOMElement,$nodeName){ if($DOMElement->getElementsByTagName($nodeName)->length==1){ return $DOMElement->getElementsByTagName($nodeName)->item(0)->nodeValue; }else{ return NULL; } } ?>

Download source code for parse XML file and insert into MySQL Database

Note: You may need to check if the product already exists in the database before import each product. Above script simply insert all products into database without check duplicates.
If you have large XML files, It may took long time to complete the inset. So PHP will give a time out error. In such case you have to manually set the time limit to zero by using set_time_limit(0); zero means no time limit. Script will be execute until it completes the data fetch. Default PHP time limit is 30 seconds. You can set preferred value for it without changing the php.ini file using above function.

59 comments:

phponwebsites said...

Thanks

Unknown said...

thank!
Trà thanh lọc cơ thể, các loại trà thanh lọc cơ thểtừ thiên nhiên: xanh, trà gừng, bà hà, hoa cúc... cung cấp rất nhiều lợi ích cho sức khỏe đặc biệt giúp thanh lọc cơ thể hiệu quả.


Các cách thanh lọc cơ thể an toàn như: Tập thể dục, xông hơi, ăn tỏi, uống trà thảo dược là những cách thanh lọc cơ thể vừa an toàn vừa hiệu quả nhất.


Các phương pháp thanh lọc cơ thể : Thanh lọc cơ thể là quá trình giải phóng các độc tố ra ngoàicơ thể, quá trình này có thể giúp bạn tránh được bệnh tật và tái tạo khả năng tối ưu hóa sức khỏe.


thanh lọc cơ thể bằng chanh: 16 tác dụng thanh lọc cơ thể với nước chanh.


Thực phẩm giúp thanh lọc cơ thể nhanh chóng với 15 loại thực phẩm quanh ta từ hôm nay sẽ đem đến cho bạn cơ thể khỏe mạnh trông thấy.


Mướp đắng hay còn gọi là khổ qua là thực phẩm chứa nhiều dưỡng chất có lợi cho sức khỏe. Khổ qua có tác dụng gì? Tác dụng của nước ép khổ qua rất hiệu quả giúp thanh lọc cơ thể, mát gan giải độc rất tốt cho cơ thể...


Cỏ lúc mì với nhiều dưỡng chất thiết yếu, nước ép cỏ lúa mì là thức uống dinh dưỡng phổ biến ở châu Âu. Và hiện nay, tác dụng thanh lọc cơ thể và giảm cân tự nhiên với nước ép cỏ lúa mì ngày càng được nhiều người áp dụng tại Việt Nam.


Những món ăn nhiệt lại càng làm cơ thể bạn thêm mệt mỏi. Thanh lọc cơ thể bằng những thực phẩm mát cho cơ thể. Với thực phẩm giải nhiệt mùa nóng dưới đây để luôn khỏe mạnh bạn nhé!


Uống nước chanh không chỉ giúp thỏa cơn khát, giải nhiệt mà còn rất tốt cho hệ tiêu hóa, làm sạch da, thanh lọc cơ thể, rất tốt cho sức khỏe. lợi ích của nước chanh...


Bí quyết thanh lọc cơ thể của Thùy Dương, Thùy Dương là một diễn viên trẻ đầy tài năng, để giữ cơ thể luôn khỏe mạnh, bắt đầu mỗi ngày Thùy Dương đã thực hiện phương pháp thanh lọc cơ thể bằng một cốc nước ấm vắt vài giọt chanh tươi và kết thúc với bài tập


Thiền buông thư được xem là một trong những phương pháp hữu hiệu nhất để thanh lọc cơ thể. Thiền buông thư giúp cơ thể bạn luôn khỏe mạnh. Hướng dẫn thiền buông thư...


shop nhí mập said...

Bài viết chia sẻ hay về phương pháp tri ho cho me bau từ thiên nhiên.khi mang thai phụ nữ rất quan tâm thực phẩm bà bầu nên ăn trong 3 tháng đầu .Mách mẹ meo tri bieng an o tre rất hay.Nếu trẻ sơ sinh bị suy dinh dưỡng thì bạn hãy xem bài viết này "trẻ sơ sinh suy dinh dưỡng".
xem thêm
tinh hoàn bên to bên nhỏ ở trẻ sơ sinh
cong dung cua qua ot
tre so sinh bi suy dinh duong
megavita

Unknown said...



thuốc trị bệnh hôi miệng hay không chỉ tôi với, vì sao bạn cần thuoc chua hoi mieng nếu bạn đang mắc phải và đang tìm hôi miệng dạ dày tôi muốn tìm các chữa chua hoi mieng tan goc thì phải làm sao cóc cách nào. Hiện nay chúng tôi BÁN BUÔN GIÀY DÉP TRẺ EM XUẤT KHẨU GIÁ SỈ có thể nói là giá re và còn nhưng mặt hàng
giày cao gót nữ Việt Nam xuất khẩu và còn những mặt hàng như NƠI MUA SẮM QUẦN ÁO GIÁ RẺ Ở TPHCM sẽ giúp bạn tha hồ lựa chọn những sản phẩm ưng ý tại website: Mattino bạn muốn duy trì tuổi thành xuân bổ sung collagen cho da
nếu cần thíc mình yêu nhau nhưng anh phải chữa hôi miệng bằng cách chữa hôi miệng dân gian nha anh yêu, em yêu anh i lớp du.... hihi



Unknown said...

Chia sẻ blogs http://sudungkemduongam.blogspot.com/
Chia sẻ blogs http://xn--kemdngdatonthn-pgb9a092ajx5q.blogspot.com/
Chia sẻ blogs http://kemduongdacuahang.blogspot.com/
Chia sẻ blogs http://kemtrinamcototkhong.blogspot.com/
Chia sẻ blogs http://bangphuongphaptunhien.blogspot.com/
Chia sẻ blogs http://xn--vnchuynhng-o4a4562glia.blogspot.com/
Chia sẻ blogs http://xn--shiphngvvitnam-kgb1053j8ca.blogspot.com
Chia sẻ blogs http://chuyenphatnhanhdi.blogspot.com/
Chia sẻ blogs http://xn--shiphngnithnh-tdbg8783j.blogspot.com/
Chia sẻ blogs http://xn--vnchuynhng-o4a4562glia.blogspot.com/
Chia sẻ blogs http://dichvuvanchuyenhanghoavietnam.blogspot.com/
Chia sẻ blogs http://vantaihanghoavietnam.blogspot.com/

1 said...
This comment has been removed by the author.
1 said...
This comment has been removed by the author.
1 said...


Thank you very much

Xe honda city - Xe honda crv

Unknown said...

Bài viết rât hay cần học hỏi thêm kinh nghiệm. Ngoài ra BV chúng tôi có các dịch vụ khác

ung thu co tu cung | ung thu phu khoa |
ung thu vu | tam soat ung thu phu khoa
Benh vien ung buou ha noi

Web Designers Pitampura said...

Nice post, things explained in details. Thank You.

Unknown said...

Một vụ nhập lậu 240 sản phẩm tân dược; 400 lọ tinh dầu diệt côn trùng, 60 hộp bột thạch rau câu và 12 gói trà xanh sữa dạng bột vừa bị Đội Kiểm soát Hải quan số 1, Cục Hải quan Quảng Ninh bắt giữ tại thang may gia dinh.

Lực lượng chức năng lập tức đuổi theo bằng dịch vụ dịch vụ vận tải, van chuyen hang hoa ra Sai Gon, van chuyen hang hoa ra Ha Noi để tiếp cận đối tượng và hàng hóa để kiểm tra. Khi lực lượng chức năng áp sát, đối tượng nhanh chóng cắt dây buộc hất thùng carton xuống đường và phóng xe với tốc độ cao để bỏ chạy van chuyen hang hoa di Phu Quoc.

Tại đây, lực lượng chức năng thu giữ tang vật gồm: 240 sản phẩm tân dược (thuốc kháng sinh, miếng dán chữa mắt cá chân, thuốc giảm đau, thuốc mỡ); 400 lọ tinh dầu diệt côn trùng, 60 hộp bột thạch rau câu và 12 gói trà xanh sữa dạng bột để vận chuyển hàng hoá đi Campuchia giá rẻvận chuyển hàng hoá đi Lào.

1 said...

Great post. Thank you very much tam soat ung thu phoi | dieu tri ung thu phoi | dieu tri ung thu vom hong | dieu tri ung thu co tu cung | dieu tri ung thu tuyen tien liet

Trung tâm IVF Hồng Ngọc said...

I can not describe because it's so great.

Khám vô sinh | Phuong phap iui | Dau hieu vo sinh nam

Benh vo sinh nam | Benh vo sinh nu | Điều trị vô sinh hiếm muộn | Thụ tinh ống nghiệm


Unknown said...

I agree with the comments you have made

dieu tri ung thu tuyen tuy | dieu tri ung thu than | dieu tri ung thu buong trung | dieu tri ung thu tuyen tien liet | dieu tri ung thu dai truc trang

Vina Giày said...

xưởng sản xuất giày dép

1 said...

I agree with the comments you have made

Xe Kia Morning | Bán xe kia morning | Xe Kia Morning 2017

Anonymous said...

We are a group of volunteers and starting a new scheme in our community.
Your website offered us with valuable info to work on. You have done an impressive
job and our entire community will be grateful to you.

Anonymous said...

F. To shut the Disk Defragmenter utility, click on the Shut button on the title
bar of the window.

Anonymous said...

This is the best place to get good collection of information with almost complete content, thanks much for sharing here and please do keep updating us...
Best Online Software Training Institute | Wordpress Training

pooja said...

Awesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..

Hadoop Training in Chennai

Hadoop Training in Bangalore

Big data training in tambaram

Big data training in Sholinganallur

Big data training in annanagar

Unknown said...

I enjoy what you guys are usually up too. This sort of clever work and coverage! Keep up the wonderful works guys I’ve added you guys to my blog roll.


MEAN stack training in Chennai

MEAN stack training in bangalore

MEAN stack training in tambaram

MEAN stack training in annanagar

MEAN stack training in Velachery

kevingeorge said...


Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

rpa training in Chennai

rpa training in anna nagar | rpa training in marathahalli

rpa training in btm | rpa training in kalyan nagar

rpa training in electronic city | rpa training in chennai

rpa online training | selenium training in training

Mounika said...

It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.
python training in rajajinagar
Python training in btm
Python training in usa

Unknown said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

java training in chennai | java training in bangalore

java online training | java training in pune

Balaji said...
This comment has been removed by the author.
nilashri said...

Thank you for benefiting from time to focus on this kind of, I feel firm about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me
Data Science training in kalyan nagar | Data Science training in OMR
Data Science training in chennai | Data science training in velachery
Data science training in jaya nagar

Anonymous said...

Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

angularjs online Training

angularjs Training in marathahalli

angularjs interview questions and answers

angularjs Training in bangalore

angularjs Training in bangalore

Anbarasan14 said...

This was helpful to me thanks for sharing this useful information. Kindly continue the work.

https://englishlabs.in/
https://englishlabs.in/spoken-english-classes-bangalore/
https://englishlabs.in/ielts-training-bangalore/
https://englishlabs.in/toefl-coaching-bangalore/
https://englishlabs.in/german-language-classes-bangalore/
https://englishlabs.in/french-language-classes-bangalore/
https://englishlabs.in/gre-coaching-bangalore/

yuvarani said...

This information is impressive. I am inspired with your post writing style & how continuously you describe this topic. Eagerly waiting for your new blog keep doing more.
www.fita.in/ccna-course-in-bangalore/
www.fita.in/cloud-computing-courses-in-bangalore/

Sumaya Manzoor said...

Great content with an excellent idea!!! Thanks for sharing.

Selenium training in Chennai
Selenium Courses in Chennai
best ios training in chennai
.Net coaching centre in chennai
French Classes in Chennai
Big Data Training in Chennai
Qtp course in Chennai
Best qtp training institute in Chennai

sheela rajesh said...

Nice blog and you gave such an innovative ideas.Thank you for sharing such kind of great things.i hope it will help
the readers.
Loadrunner Training in Chennai
French Classes in Chennai
Android Training in Chennai
Digital Marketing Course in Chennai
German Courses in Chennai
German Classes in Chennai
German classes in Velachery

KIT said...

Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
Kindly visit us @ 100% Job Placement | Best Colleges for Computer Engineering
Biomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu
Biotechnology Colleges in Coimbatore | Biotechnology Courses in Coimbatore
Best MCA Colleges in Tamilnadu | Best MBA Colleges in Coimbatore
Engineering Courses in Tamilnadu | Engg Colleges in Coimbatore



Venkatesh CS said...

Really useful information. Thank you so much for sharing. hadoop interview questions
Hadoop interview questions for experienced
Hadoop interview questions for freshers
top 100 hadoop interview questions
frequently asked hadoop interview questions
hadoop interview questions and answers for freshers
hadoop interview questions and answers pdf
hadoop interview questions and answers
hadoop interview questions and answers for experienced
hadoop interview questions and answers for testers
hadoop interview questions and answers pdf download

Chris Hemsworth said...

The article is so informative. This is more helpful for our
Best online software testing training course institute in chennai with placement
Best selenium testing online course training in chennai
Learn best software testing online certification course class in chennai with placement
Thanks for sharing.

Sivakumari.B said...

Your info is really amazing with impressive content..Excellent blog with informative concept. Really I feel happy to see this useful blog, Thanks for sharing such a nice blog..
If you are looking for any Data science Related information please visit our website best course for data science page!

Tripu Design said...

who provides Graphic services, web designing services, logo design services, graphic design
and all kind of website design,Graphic services.
Freelance Graphic Designing:
Freelance Catalogue Designing in delhi
Freelance Catalogue Designing in gurgaon
Freelance Brochure Designing
Freelance Label Designing
Freelance Banner Designer
Freelance Poster Designer
graphic design services in delhi
graphic design services in gurgaon
Freelance Catalogue Designing in delhi
Freelance Catalogue Designing in gurgaon
Freelance Brochure Designing
Freelance Label Designing
Freelance Banner Designer
Freelance Poster Designer
graphic design services in delhi
graphic design services in gurgaon
Freelance Catalogue Designing in delhi
Freelance Catalogue Designing in gurgaon
Freelance Brochure Designing
Freelance Label Designing
Freelance Banner Designer
Freelance Poster Designer
graphic design services in delhi
graphic design services in gurgaon
Freelance Catalogue Designing in delhi
Freelance Catalogue Designing in gurgaon
Freelance Brochure Designing
Freelance Label Designing
Freelance Banner Designer
Freelance Poster Designer
graphic design services in delhi
graphic design services in gurgaon

shri said...

excellent...!
internship in chennai for ece students
internships in chennai for cse students 2019
Inplant training in chennai
internship for eee students
free internship in chennai
eee internship in chennai
internship for ece students in chennai
inplant training in bangalore for cse
inplant training in bangalore
ccna training in chennai


Shadeep Shree said...

Awesome article! You are providing us very valid information. This is worth reading. Keep sharing more such articles.
Data Science Course in Chennai
Data Science Classes in Chennai
R Training in Chennai
AWS Training in Chennai
Data Science Training in Guindy
Data Science Training in Thiruvanmiyur
Data Science Training in Anna Nagar

Shanthi Cabs said...

Keep sharing the post like this.

SS Vermicompost Industry said...

Thanks for posting such a great blog
Vermicompost Manufacturers | Vermicompost in chennai

SS Vermicompost Industry said...



Thanks for sharing such a great blog
Vermicompost manufacturers in Tamilnadu | Vermicompost in Tamilnadu
Vermicompost Manufacturers | Vermicompost Suppliers
Vermicompost in Coimbatore | Vermicompost manufacturers in Chennai
Vermicompost in chennai | Best Vermicompost in chennai
.

Venna said...

https://hiburan.club/
http://jalanjala.com/
https://hiburanmalam.com/
https://casinolive.me/
https://infobola.info/

Sathya Shopping said...


Hi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | Corporate gifts wholesale Singapore
Business card holder singapore | T shirts supplier singapore
Thumb drive supplier singapore | Leather corporate gifts singapore

tjproductstech said...



Hi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | corporate gifts supplier

Jayalakshmi said...

Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic. Thanks for the purpose of giving such terrific data...
sap training in chennai

sap training in tambaram

azure training in chennai

azure training in tambaram

cyber security course in chennai

cyber security course in tambaram

ethical hacking course in chennai

ethical hacking course in tambaram

shiny said...

This is the best place to get good collection of information with almost complete content, thanks much for sharing here and please do keep updating us ...



data science training in chennai

data science training in annanagar

android training in chennai

android training in annanagar

devops training in chennai

devops training in annanagar

artificial intelligence training in chennai

artificial intelligence training in annanagar


jeni said...

Its such as you learn my mind! You appeаr tо grasp ѕo much approximately this, such as you wrote the book in it or something.
I think that you could ɗo wіth some percent to pressure the mesѕage home a little bit,
but instead of that, this iѕ excellent blog. An excellent
read. I ԝilⅼ defіnitely be back.
angular js training in chennai

angular js training in velachery

full stack training in chennai

full stack training in velachery

php training in chennai

php training in velachery

photoshop training in chennai

photoshop training in velachery


vantaiconthoi.vn - Vận tải Con thoi said...

Cảm ơn bạn đã chia sẻ, nếu cần vận chuyển hàng đi campuchia thì a/c liên hệ bên mình nhé. Hotline: 0903751981, website: https://vantaiconthoi.vn/chanh-xe-van-chuyen-hang-di-campuchia

lavanya said...

Its such as you learn my mind! You appeаr tо grasp ѕo much approximately this, such as you wrote the book in it or something.salesforce training in chennai

software testing training in chennai

robotic process automation rpa training in chennai

blockchain training in chennai

devops training in chennai

siva said...

Excellent article for the people who need information about this course.
salesforce certification courses
interview tips and tricks
what to do after bsc
data science tools and technologies
oracle pl sql interview questions
pega testing interview questions

Atlanta GA said...

 Water Damage Restoration & Repair Plantation, Florida
Water Damage Restoration & Mold Removal - Boca Raton Florida
Water Damage Restoration in Davie, Florida Fire and Mold Cleanup
water damage restoration deerfield Florida
water damage & Restoration fort lauderdale, Florida
water damage Pembroke,restoration Services Pembroke, Florida
water damage & restoration Hollywood, FL

SixD Engineering Solutions Pvt Ltd said...

You always come up with new and interesting ideas, love your videos and suggestions.
3D Scanning Services Near Me
3D Laser Scanning Targets
3D Scanning Reverse Engineering

ali said...

Nice post. It is really interesting. Thanks for sharing the post!

Oppo A11k 32GB 2GB Smartphone v2kart.xyz
Realme 3 Pro (Lightning Purple, 128 GB) (6 GB RAM) Refurbished v2kart.xyz

Hi Every One said...

AnyToISO Professional 3.9.8 registration code You can convert a format to ISO at any time. It is the ultimate Optical Disk Imaging Utility AnytoISO Crack Mac

Let2know said...

Mixed In Key Crack the application form employs an exceptional algorithm to both spot and also rescue the results into some database. Website

Jennifer said...


Your website is awesome. I used a lot of what it had to say.
SwitchResX

iteducationcentre said...

Great explanation...Thanks for explaining in such a nice manner...
MEAN Stack training in Pune

Adam said...


Very excellent post!!! Thank you so much for your great content. Keep posting.....
AWS Course in Chennai

CrackzSoftware said...

Informational blog.Revo Uninstaller Pro Crack