เมื่อใช้ simplexml_load_file() เรียกไฟล์ xml เข้ามา มันจะสร้าง object SimpleXMLElement ขึ้น ยกตัวอย่างจาก http://www.thairath.co.th/rss/life.xml
[0] => SimpleXMLElement Object
(
[title] => "แฟรงเคนวีนนี่" เสื้อยืดลายพิเศษสไตล์ 'ทิมเบอร์ตัน'
[guid] => http://www.thairath.co.th/content/life/295631
[description] => ยูนิโคล่ นำเสนอเสื้อยืด UT คอลเลกชั่น “แฟรงเคนวีนนี่” เสื้อยืดดีไซน์พิเศษ ต้อนรับภาพยนตร์เรื่องล่าสุดของ 'ทิม เบอร์ตัน' ผู้กำกับ อลิซ อิน วันเดอร์แลนด์
[link] => http://www.thairath.co.th/content/life/295631
[enclosure] => SimpleXMLElement Object
(
[@attributes] => Array
(
[url] => http://www.thairath.co.th/media/content/2012/10/03/295631/hr1667/120.jpg
[type] => image/jpeg
)
)
[pubDate] => Wed, 03 Oct 2012 16:00:00 +0700
)
ถ้าต้องการแสดง title จะใช้ foreach แบบนี้
$xml = simplexml_load_file('http://www.thairath.co.th/rss/life.xml');
foreach ($xml->channel->item as $row) {
echo $row->title.'< br >';
}
ผลที่ได้ คือ
'ออรัล เซ็กซ์'สัมผัส(ลับ)อันตราย…โดนแล้วเป็นติดใจ!!!
เนื้อตาย ตาบอด ฉีดฟิลเลอร์ อันตรายกว่าที่คิด!
คลอดแล้ว คอลเลกชั่นที่ 7 IKEA PS 2012...!
สาวสวย-หนุ่มหล่อ ประชันออร่า ฉายแววเซเลบฯ
SHELL FERRARI 500 RACES เมื่อปฏิสัมพันธ์ ก่อกำเนิดเชื้อเพลิงคุณภาพ (ตอนที่1)
ตัน อิชิตัน ! ทำเซอร์ไพรส์แจกทองคำ 1 ล้านบาท ลูกสาวคนขับแท็กซี่เฮง..!
เผยโฉม 'ปัญญ์ปุริ' บูทีคความงามจากธรรมชาติบนเกาะสมุย
หากต้องการ description ก็เพียงแค่เพิ่ม
$row->description
แต่ปัญหาในทีนี้อยู่ที่ enclosure เพราะว่ามันไม่ได้เป็นแค่ tag ของ object แรกเท่านั้น แต่มันเป็นอีก object หนึ่งที่อยู่ภายใน item วิธีการเรียกใช้งานก็ไม่ยากนัก ดังนี้
รูปแบบตอนที่ print_r() ออกมา
[@attributes] => Array
(
[url] => http://www.thairath.co.th/media/content/2012/10/03/295631/hr1667/120.jpg
[type] => image/jpeg
)
วิธีการเรียกจะต้องใช้แบบนี้
$xml = simplexml_load_file('http://www.thairath.co.th/rss/life.xml');
foreach ($xml->channel->item as $row) {
echo $row->enclosure->attributes()->url.'< br >';
}
ผลที่ได้คือ
http://www.thairath.co.th/media/content/2012/10/01/295180/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/10/02/295393/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/10/02/295370/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/10/01/295151/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/10/01/295199/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/10/01/295105/hr1667/120.jpg
http://www.thairath.co.th/media/content/2012/09/29/294772/hr1667/120.jpg
ป้ายกำกับ: coding, feed, php, rss, xml