douguachi0056 2010-08-01 20:34
浏览 48
已采纳

通过PHP检索XML页面的元素

I'm trying to wrap my head around PHP and XML.

I'm trying to do something:

There is an XML document that I'm retrieving via cURL (also tried various PHP XML library parameters such as XMLReader::open($url) etc. The method of retrieval doesn't matter; I can and have got this part working.

The problem is parsing the XML on the retrieved page.

Here is an example of the XML:

http://z3950.loc.gov:7090/voyager?version=1.1&operation=searchRetrieve&query=9780471615156&maximumRecords=1&recordPacking=xml&recordSchema=marcxml

What I need to get from that page is the call number;

<datafield tag="060" ind1=" " ind2=" ">
  <subfield code="a">WM 173.6 R823m</subfield>
</datafield>

author;

<datafield tag="100" ind1="1" ind2=" ">
  <subfield code="a">Ross, Colin A.</subfield>
</datafield>

and title information;

<datafield tag="245" ind1="1" ind2="0">
  <subfield code="a">Multiple personality disorder :</subfield>
  <subfield code="b">diagnosis, clinical features, and treatment /</subfield>
  <subfield code="c">Colin A. Ross.</subfield>
</datafield>

seems simple enough. However, for the life of me I can not seem to get any of the inbuilt PHP functions for working with XML to work (because I'm doing it wrong).

Here is an example I've tried:

//xml file retrieved via curl and saved to folder
$file="9780471615156.xml";

$xml = simplexml_load_file($file);

echo $xml->getName();//returns searchRetrieveResponse

foreach($xml->searchRetrieveResponse[0]->attributes() as $a => $b){
  echo $a,'="',$b,"\"</br>";//nothing
 }

foreach ($xml->searchRetrieveResponse[0]->children() as $child){
  echo "Child node: " . $child . "<br />";//nothing
}

it returns the name of the first node, but I can't get it to go any deeper.

NB: I'm running PHP 5+

  • 写回答

3条回答 默认 最新

  • doyp9057 2010-08-01 21:04
    关注

    as far as I tried the simpleXML can not read this XML. Try the example below, it will list an array which you can easily loop trought and find what you need simply by comparing keys/values you're looking for.

    // load XML into string here
    // $string = ????;
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $string, $object, $index);
    
    echo '<pre>';
    print_r($object);
    // print_r($index);
    echo '</pre>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真