PHP5cungcấpclassSimpleXMLlàmộtclassrấtdễsửdụng,bàinàysẽhướngdẫncác
bạnparsefileXMLtrong7nốtnhạc.
Đầutiên,lấymộtđoạnXMLmẫuđểtậptànhphântích:
PHPCode:(ClickHeretoSelectAll)
<?xmlversion="1.0"?>
<books>
<bookisbn="9781594489501">
<title>AThousandSplendidSuns</title>
<author>KhaledHosseini</author>
<publisher>RiverheadHardcover</publisher>
<amazon_price>14.27</amazon_price>
</book>
<bookisbn="9781594489587">
<title>TheBriefWondrousLifeofOscarWao</title>
<author>JunotDiaz</author>
<publisher>RiverheadHardcover</publisher>
<amazon_price>14.97</amazon_price>
</book>
<bookisbn="9780545010221">
<title>HarryPotterandtheDeathlyHallows</title>
<author>J.K.Rowling</author>
<publisher>ArthurA.LevineBooks</publisher>
<amazon_price>19.24</amazon_price>
</book>
</books>
ĐểtoramộtđốitượngSimpleXmlElement,cáchđơngiảnlàtruynvàomtchuỗihoặc
mtfile:
//PassingtheXML
$books=SimpleXMLElement($XmlData);
//
//Passingafilename
$books=SimpleXMLElement('books.xml',null,true);
NhìnvàođoạnXMLvídụ,tasẽlyrattcảcácbookhaycủaAmazon:
PHPCode:(ClickHeretoSelectAll)
<?php
//loadSimpleXML
$books=newSimpleXMLElement('books.xml',null,true);
echo<<<EOF
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>PriceatAmazon.com</th>
<th>ISBN</th>
</tr>
EOF;
foreach($booksas$book)//loopthroughourbooks
{
echo<<<EOF
<tr>
<td>{$book>title}</td>
<td>{$book>author}</td>
<td>{$book>publisher}</td>
<td>${$book>amazon_price}</td>
<td>{$book['isbn']}</td>
</tr>
EOF;
}
echo'</table>';
?>
Bạnđểýrằng$books(cóchữ's'nhé)làmộtElementdokháiniệmmi
mtfileXMLtphảicórootelement.thế,đừngmongđợicóđối
tượngSimpleXmlkhôngnhé .
Mỗielementcóthểcónhiềuelementconcùngloihaykhácloi,dụ
nàylàcùngloi'book'vàclassSimpleXmlElementnàychophéptaduyệt
quacácelementconcùngloinhưmtarraynhưvídụforeach()ởtrên.
Cuốicùng,nóivềcúpháptruycậpchildelementvàattribute.Bácnàochưabiếtkhái
niệmynữathì:
PHPCode:(ClickHeretoSelectAll)
<bookisbn="9781594489501">
<title>AThousandSplendidSuns</title>
<author>KhaledHosseini</author>
<publisher>RiverheadHardcover</publisher>
<amazon_price>14.27</amazon_price>
</book>
isbnlàmtattribute,cácgiátrcủamtattributephảiđểtrongdấu(")
<title>,<author>,...làcácchildelement
Chỉgiảithíchtớiđâyti,bácnàocóý địnhngâmcứuXML,XMLSchema,...t5sgợi
ýlànên...từbỏýđnhngôngcuốngthừathờigiannàyđicócảnămmayrahcmi
xongmàhọcttháng112ttớitháng12sẽquêntháng1 .Cứviệccoinónhưkhái
niểmHTMLđãhọcrồixàichothoảimáinhá.
Quayvềcúpháp,lạicoivídụ'simple'trên:$book>titlelàtruycậpchildelementtrong
khi$book['isbn']làtruycậpattribute.Done!!!
Đơngiảnthếthôi,bạnthấyxửXMLdatacódễchưa?
Vídụtrên,nếubạnkhôngtchdụngforeachthìcóthểdùngbiếncounter$i,viếtli
$tempBook=$books>book[$i]rồi dùng$tempBookđểxửlý.
GiờthêmvàotíXPathchonóbằnganhbằngem:
XPathđơnginlàcáchchỉrađườngdẫn"path"trong1XMLdocumentthôngquacác
elementcha/contheocúphápgiốngnhưthưmụccủalinux:/home/user/...Xpathgiúp
bạnlcracácchildelementtrongcácelementchacùngloại,gomlithànhmảngvàxử
.
VídụsaugiúpbạnlyratấtcảcáctitlecủabookvàtấtcảcácsốISBN:
PHPCode:(ClickHeretoSelectAll)
$titles=$books>xpath('book/title');
foreach($titlesas$title)
{
echo$title.PHP_EOL;
}
//////////////////////////////////////////////
$isbn=$books>xpath('book/@isbn');
foreach($isbnas$isbn)
{
echo$isbn.PHP_EOL;
}
Nhớchúýcáchdùngcúpháp/và/@nhé.
GiờparsethửRSScủatuổitrẻcoisaonè
PHPCode:(ClickHeretoSelectAll)
<?php
$rss=newSimpleXMLElement('http://www.tuoitre.com.vn/tianyon/RssView.
aspx?ChannelID=16',null,true);
echo"<h1><ahref='{$rss>channel>link}'>{$rss>channel
>title}</a></h1>".PHP_EOL.'<hr/>'.PHP_EOL;
foreach($rss>xpath('channel/item')as$item)
{
echo<<<EOF
<h2><ahref='{$item>link}'>{$item>title}</a></h2>
<div>Postedat:{$item>pubDate}</div>
{$item>description}
<hr/>
EOF;
}
?>
Cuốicùng,mtvàithuộctínhcủađốitượngSimpleXmlElementcácbạnsẽquantâm:
PHPCode:(ClickHeretoSelectAll)
$value =trim((string)$element); //BảnthênelementnólàXML,
bạnlấygiátrịcủaelementthìépkiểuvềstring
$attributes=$element>attributes(); //lấytấtcảcácattribute
$children =$element>children(); //lấycácchildelement