เช่น เราต้องการแปลงข้อมูลในไฟล์ allResults.xml ให้เป็นตารางในไฟล์ HTML ดังแสดงในรูปที่ 1 และรูปที่ 2
รูปที่ 1
รูปที่ 2
ในการแปลงข้อมูลนั้นมีได้หลายวิีธี
1) อาจจะเขียนไฟล์ XSL ที่ไปดึงข้อมูลจาก allResults.xml โดยตรงก็ได้
2) ใช้ XML parser เพื่อดึงข้อมูลจาก allResults.xml แล้วเก็บไว้ในไฟล์ results.xml เพื่อให้เขียนไฟล์ XSL ได้ง่ายขึ้น
<?php
// โค้ดนี้ใช้วิธีที่ 2 ซึ่งใช้ XML parser เพื่อดึงข้อมูลจาก allResults.xml
// แล้วเก็บไว้ในไฟล์ results.xml เพื่อให้เขียนไฟล์ XSL ได้ง่ายขึ้น
// เขียน XML declaration ในไฟล์ xml results.xml
$xml_result = "";
$xml_result .= "
// อ่านข้อมูลจากไฟล์ allResults.xml
$xml = simplexml_load_file("allResults.xml");
// เขียนข้อมูลของอิลิเมนต์ Theater ลงในไฟล์ results.xml
foreach ($xml->GetTheatersAndMoviesResult->Theater as $theater) {
$xml_result .= '
$xml_result .= htmlspecialchars($theater->Name);
$xml_result .= '
$xml_result .= htmlspecialchars($theater->Address);
$xml_result .= '
}
$xml_result .="
// บันทึกข้อมูลลงไปในไฟล์
$fp = fopen('results.xml','w');
$write = fwrite($fp,$xml_result);
fclose($fp);
// เริ่มทำการแปลงโดยสร้างออปเจตก์ DOMDocument และ XSLTProcessor
$doc = new DOMDocument();
$xsl = new XSLTProcessor();
$xsl_filename = "results.xsl";
// โหลดข้อมูลจากไฟล์ XSL
$doc->load($xsl_filename);
// ระบุว่าให้ใช้ XSLTProcessor สำหรับออปเจกต์ DOM ที่สร้างขึ้นมา
$xsl->importStyleSheet($doc);
$xml_filename = "results.xml";
// โหลดข้อมูลจากไฟล์ XML
$doc->load($xml_filename);
// แสดงผลที่ได้จากการแปลงข้อมูล
echo $xsl->transformToXML($doc);
?>
// ไฟล์ XSL
ไม่มีความคิดเห็น:
แสดงความคิดเห็น