开发者

PHP read XML properties

I have the following XML data which is generated by a webservice

<?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开发者_Python百科="New York [u.a.]"    url="http://www.worldcat.org/oclc/263710087?referer=xid">9780439139601</isbn>

</rsp>

I need to read the data in the 'isbn' tag, more specifically, the value of the property 'title'. How would I do this in PHP.

Thanks


With DOM

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

With SimpleXml:

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

Just my 2c why you want to use DOM: SimpleXML appears simple indeed, but simplicity in this case means lack of control. DOM isn't much harder to use and can do more. DOM is an Interface Standard defined by the W3C and can be found implemented in many languages, so it pays to know the API. True, it might be a bit more verbose than SimpleXML but it's also ultimately more powerful. If you have worked with DOM for some time, you don't want to go back.


Using SimpleXML, or DOM. Here are some usage examples : http://www.php.net/manual/en/simplexml.examples-basic.php


I have solved this myself.

$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'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜