代码之家  ›  专栏  ›  技术社区  ›  Señor Reginold Francis

PHP读取XML属性

  •  0
  • Señor Reginold Francis  · 技术社区  · 16 年前

    我有以下由webservice生成的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'标签中的数据,更具体地说,是属性'title'的值。我将如何在PHP中做到这一点。

    谢谢

    3 回复  |  直到 16 年前
        1
  •  4
  •   Gordon Haim Evgi    16 年前

    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'];
    }
    

    这就是为什么要使用DOM:SimpleXML看起来确实很简单,但在本例中,简单意味着缺乏控制。DOM使用起来并不难,而且可以做得更多。 DOM is an Interface Standard defined by the W3C 而且可以用多种语言实现,因此了解API是值得的。诚然,它可能比SimpleXML更冗长一些,但它最终也更强大。如果你和DOM共事了一段时间,你就不想回去了。

        2
  •  0
  •   greg0ire    16 年前
        3
  •  0
  •   Señor Reginold Francis    16 年前

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