2010-06-21 98 views
0

我具有由web服務所生成的以下XML數據PHP讀取XML屬性

<?xml version="1.0" encoding="UTF-8"?> 
<rsp xmlns="http://worldcat.org/xid/isbn/" stat="ok"> 
     <isbn oclcnum="263710087 491996179 50279560 60857040 429386124 44597307" lccn="00131084" form="AA BC" year="2002" lang="eng" ed="1st American ed." title="Harry Potter and the goblet of fire" author="J.K. Rowling." publisher="Scholastic Inc." city="New York [u.a.]" url="http://www.worldcat.org/oclc/263710087?referer=xid">9780439139601</isbn> 

</rsp> 

我需要在「ISBN」標籤讀取數據,更具體地,屬性「標題」的值。我將如何在PHP中執行此操作。

感謝

回答

0

我自己解決了這個問題。

$xmldata= file_get_contents("http://xisbn.worldcat.org/webservices/xid/isbn/9780439139601?method=getMetadata&format=xml&fl=*"); 
$xml= new SimpleXMLElement($xmldata); 
print $xml->isbn[0]['title']; 
+2

這取決於你在xml中有多少個isbn標籤。只會得到你第一個標籤元素的標題。 我想你應該使用像戈登建議的東西。 – Youssef 2010-06-21 15:04:51

4

隨着DOM

$dom = new DOMDocument; 
$dom->load('books.xml'); // or from URL  
foreach($dom->getElementsByTagName('isbn') as $node) { 
    echo $node->getAttribute('title'); 
} 

隨着SimpleXml

$sxe = simplexml_load_file('filename.xml'); // or from URL 
foreach($sxe->isbn as $node) { 
    echo $node['title']; 
} 

只是我2C爲什麼要使用DOM:SimpleXML的出現簡單確實,但簡單在這種情況下,意味着缺乏控制。 DOM不是很難使用,可以做更多。 DOM is an Interface Standard defined by the W3C,並且可以在許多語言中實現,所以知道API是值得的。誠然,它可能比SimpleXML更冗長,但它最終也更強大。如果你已經使用DOM一段時間了,你不想回去。