ตัวอย่างการ Parsere XML ด้วย PHP #1

PHP - XML Parser ตัวอย่างการแปลงเอ็กเอ็มแอลด้วยพีเอชพี

เอามาฝากจากแลปเอ็กเอ็มแอลเทอมที่แล้ว ที่ผมได้จากการเรียนวิชา “เอ็กเอ็มแอล” และเห็นว่ามันได้ใช้ประโยชน์จริงๆ และมีประโยชน์มักมากเลยครับ กับการแปลงข้อมูลในฟอร์แมตเอ็กเอ็มแอล หรือการอ่านข้อมูลจากเอ็กเอ็มแอลนั่นแหละ งานนี้ก็ต้องขอบพระคุณไปถึงอาจารย์ “กานดา” อาจารย์ประจำวิชาของผมเองครับ เข้าเรื่องกันเลย

สมมติเราอยากจะอ่านเอ็กเอ็มแอลมาซักที่นึง ในที่นี้จะยกตัวอย่างด้วยเอ็กเอ็มแอล RSS Version 2.0 เลยละกันครับ โดยทั่วไปมันจะมีโครงสร้างดังนี้


<rss version="2.0">
<channel>
<title>
Title Rss
</title><item>
<title>Title Item</title>
<link>https://EzineArticles.com/6269640</link>
<guid>https://EzineArticles.com/6269640</guid>
<pubDate>Mon, 16 May 2011 16:04:18 -0500</pubDate>
<description>
Learn how to draw step by step and you will be sketching the cartoons of your choice before too long at all. Cartoon characters are fabulous to draw as well as watch.
</description>
</item>
</channel>
</rss>

ปกติมันจะมีหลายๆ การเข้าไปอ่านข้อมูลแต่ละ item ก็ทำได้ง่ายๆ ดังนี้จร้า

<?php
header ('Content-type: text/html; charset=utf-8');
$dom = new domDocument;
$dom->load('https://feeds.ezinearticles.com/category/Arts-and-Entertainment:Animation.xml');
$s = simplexml_import_dom($dom);
$i=0;
while($s->channel[0]->item[$i]->title) {
echo "==>item<br/>
title = ".$s->channel[0]->item[$i]->title."<br/>
link = ".$s->channel[0]->item[$i]->link."<br/>
author = " .$s->channel[0]->item[$i]->author."<br/>
Desc = " .$s->channel[0]->item[$i]->description."<br/>
==>/item<br/>";
$i++;
}
?>

จากตัวอย่างเป็นการโหลดไฟล์เอ็กเอ็มแอลมาจาก https://feeds.ezinearticles.com/category/Arts-and-Entertainment:Animation.xml
เผื่อมีอะไรตกหล่น จึงสกรีนแนบมาด้วยเลยนะคร๊าฟ

หรือจะดาวน์โหลดไฟล์พีเอชพีไฟล์นี้ไปดูเลยก็ได้ครับ >> XML PARSE.php <<

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *

This site uses Akismet to reduce spam. Learn how your comment data is processed.