Search code examples
phpxmlcurldomxpath

CURL to grab an XML file associated with this URL


I am trying to use CURL to grab an XML file associated with this URL, then i am trying to parse the xml file using DOMxPath.

There are no output errors at this point it is just not displaying anything, i tried to catch some errors but i was unable to figure it out, any direction would be amazing.

<?php
if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

function tideTime() {


$ch = curl_init("http://tidesandcurrents.noaa.gov/noaatidepredictions/NOAATidesFacade.jsp?datatype=XML&Stationid=8721138");
$fp = fopen("8721138.xml", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);

curl_close($ch);
fclose($fp);

$dom = new DOMDocument();
@$dom->loadHTML($ch);
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//time");

$arr = array();
foreach ($entries as $entry) {

  $tide = $entry->nodeValue;

}
echo $tide;

}
?>

Solution

  • Youre trying to load the curl resource handle as the DOM which it is not. the curl functions either output directly or output to string.

    $ch = curl_init("http://tidesandcurrents.noaa.gov/noaatidepredictions/NOAATidesFacade.jsp?datatype=XML&Stationid=8721138");
    $fp = fopen("8721138.xml", "w");
    
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    
    $data = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    $dom = new DomDocument();
    $dom->loadHTML($data);
    // the rest of the code