Section Artikel
PHP SimpleXML – Dapatkan Nilai Node
Dapatkan nilai node dari file “note.xml”:
Contoh:
<?php $xml=simplexml_load_file("note.xml") or die("Error: Cannot create object"); echo $xml->to . "<br>"; echo $xml->from . "<br>"; echo $xml->heading . "<br>"; echo $xml->body; ?>
Output dari kode di atas adalah:
Tove
Jani
Reminder
Jangan lupa minggu ini!
File XML lainnya
Asumsikan kita memiliki file XML bernama “books.xml”, yang terlihat seperti ini:
<?xml version="1.0" encoding="utf-8"?> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en-us">XQuery Kick Start</title> <author>James McGovern</author> <year>2003</year> <price>49.99</price> </book> <book category="WEB"> <title lang="en-us">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
PHP SimpleXML – Dapatkan Nilai Node dari Elemen Tertentu
Contoh berikut mendapatkan nilai simpul dari elemen di elemen <book> pertama dan kedua di file “books.xml”:
Contoh :
<?php $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object"); echo $xml->book[0]->title . "<br>"; echo $xml->book[1]->title; ?>
Output dari kode di atas adalah:
Everyday Italian
Harry Potter
PHP SimpleXML – Dapatkan Nilai Node – Loop
Contoh berikut mengulang melalui semua elemen dalam file “books.xml”, dan mendapatkan nilai simpul dari elemen , <author>, <year>, dan <price>:
Contoh :
<?php $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object"); foreach($xml->children() as $books) { echo $books->title . ", "; echo $books->author . ", "; echo $books->year . ", "; echo $books->price . "<br>"; } ?>
Output dari kode di atas adalah:
Everyday Italian, Giada De Laurentiis, 2005, 30.00
Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95
PHP SimpleXML – Dapatkan Nilai Atribut
Contoh berikut mendapatkan nilai atribut dari atribut “kategori” dari elemen <book> pertama dan nilai atribut dari atribut “lang” dari elemen <title> di elemen <book> kedua:
Contoh :
<?php $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object"); echo $xml->book[0]['category'] . "<br>"; echo $xml->book[1]->title['lang']; ?>
Output dari kode di atas adalah :
COOKING
en
PHP SimpleXML – Dapatkan Nilai Atribut – Loop
Contoh berikut mendapatkan nilai atribut dari elemen di file “books.xml”:
Contoh :
<?php $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object"); foreach($xml->children() as $books) { echo $books->title['lang']; echo "<br>"; } ?>
Output dari kode di atas adalah :
en
en
en-us
en-us