开发者

Problem getting XPath working in PHP

I've been trying to access the NHS API using different methods to read in the XML.

Here is a snippet of the XML:

<feed xmlns:s="http://syndication.nhschoices.nhs.uk/services" xmlns="http://www.w3.org/2005/Atom">
 <title type="text">NHS Choices - GP Practices Near Postcode - W1T4LB - Within 5km</title>
 <entry>
  <id>http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/27369</id>
  <title type="text">Fitzrovia Medical Centre</title>
  <updated>2011-08-20T22:47:39Z</updated>
  <link rel="self" title="Fitzrovia Medical Centre" href="http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/27369?apikey="/>
  <link rel="alternate" title="Fitzrovia Medical Centre" href="http://www.nhs.uk/ServiceDirectories/Pages/GP.aspx?pid=303A92EF-EC8D-496B-B9CD-E6D836D13BA2"/>
  <content type="application/xml">
   <s:organisationSummary>
    <s:name>Fitzrovia Medical Centre</s:name>
    <s:address>
     <s:addressLine>31 Fitzroy Square</s:addressLine>
     <s:addressLine>London</s:addressLine>
     <s:postcode>W1T6EU</s:postcode>
    </s:address>
    <s:contact type="General">
     <s:telephone>020 7387 5798</s:telephone>
    </s:contact>
    <s:geogr开发者_如何转开发aphicCoordinates>
     <s:northing>182000</s:northing>
     <s:easting>529000</s:easting>
     <s:longitude>-0.140267259415255</s:longitude>
     <s:latitude>51.5224357586293</s:latitude>
    </s:geographicCoordinates>
    <s:Distance>0.360555127546399</s:Distance>
   </s:organisationSummary>
  </content>
 </entry>
</feed>

I've been using this PHP to access it:

<?php

$feedURL = 'http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/postcode/W1T4LB.xml?apikey=&range=5';

$raw = file_get_contents($feedURL);

$dom = new DOMDocument();
$dom->loadXML($raw);

$xp = new DOMXPath($dom);
$result = $xp->query("//entry"); // select all entry nodes

print $result->item(0)->nodeValue;

?>

Problem is I have no results, the $raw data is present, but the $dom never gets filled with the string XML. This means the XPath won't work.

Also... for bonus points: how do I access the <s:Name> tag using XPath in this instance??

Appreciate the help as always.

Edit:

Here is the resulting PHP that worked fine, thanks to @Andrej L

<?php   

$feedURL = 'http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/postcode/W1T4LB.xml?apikey=&range=5';
$xml = simplexml_load_file($feedURL);
$xml->registerXPathNamespace('s', 'http://syndication.nhschoices.nhs.uk/services');
$result = $xml->xpath('//s:name');

foreach ($result as $title)
{
    print $title . '<br />';    
}

?>


  1. I think it's better to use SimpleXml library. see http://www.php.net/manual/en/book.simplexml.php

  2. Register namespace using http://www.php.net/manual/en/simplexmlelement.registerxpathnamespace.php

  3. Use xpath method. See http://www.php.net/manual/en/simplexmlelement.xpath.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜