简体   繁体   中英

How to access values from XML URL directly using PHP

I have this URL:

http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=bath.isbn%3D9781452110103

which returns an XML response , I want to fetch it's values directly without looping through the whole content, so far I've accessed only the name of the root node of the XML that is $str=$xml->getName(); . So is there any way I can access the rest of the nodes .

Below is the sample XML that get returns from the URL.

<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/">
<zs:version>1.1</zs:version>
<zs:numberOfRecords>2</zs:numberOfRecords>
<zs:records>
<zs:record>
<zs:recordSchema>marcxml</zs:recordSchema>
<zs:recordPacking>xml</zs:recordPacking>
<zs:recordData>
<record xmlns="http://www.loc.gov/MARC21/slim">
<leader>01517cam a2200277 i 4500</leader>
<controlfield tag="001">17092185</controlfield>
<controlfield tag="005">20150720141836.0</controlfield>
<controlfield tag="008">111221s2011 caua 000 0 eng</controlfield>
<datafield tag="906" ind1=" " ind2=" ">
<subfield code="a">7</subfield>
<subfield code="b">cbc</subfield>
<subfield code="c">orignew</subfield>
<subfield code="d">1</subfield>
<subfield code="e">ecip</subfield>
<subfield code="f">20</subfield>
<subfield code="g">y-gencatlg</subfield>
</datafield>
</zs:recordData>
<zs:recordPosition>2</zs:recordPosition>
</zs:record>
</zs:records>
<zs:echoedSearchRetrieveRequest>
<zs:version>1.1</zs:version>
<zs:query>bath.isbn=9781452110103</zs:query>
<zs:maximumRecords>10</zs:maximumRecords>
<zs:recordPacking>xml</zs:recordPacking>
<zs:recordSchema>marcxml</zs:recordSchema>
</zs:echoedSearchRetrieveRequest>
</zs:searchRetrieveResponse>

Maybe it is an option for you to use simplexml_load_file with xpath .

First you have to register the namespace . You can then change the xpath expression for the thing you are searching for.

For example:

$xml = simplexml_load_file("http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=bath.isbn%3D9781452110103");
$xml->registerXPathNamespace("slim", "http://www.loc.gov/MARC21/slim");
$path = '/zs:searchRetrieveResponse/zs:records/zs:record[1]/zs:recordData/slim:record[1]/slim:datafield[1]/slim:subfield[@code="c"]';
$result = $xml->xpath($path)[0];
echo $result;

Will result in:

orignew

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM