如何访问ssl或https类型域的xml文件并使用php存储在我们的服务器中

问题描述:

I want to access an XML file stored on another domain. The domain has an SSL certificate. I want to store it in my server folder. How can I achieve this in PHP? I am able to download without HTTPS from other sites, but unable to do it with HTTPS.

<?PHP
    $dom = new DOMDocument();
    $dom->load('www.123.com/abc.xml');
    $dom->save('filename.xml');
?>

We are going to use Curl to download this file. There are 2 option.

  1. The quick fix
  2. The proper fix

The quick fix, first.

Warning: this can introduce security issues that SSL is designed to protect against.

set:

  1. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); to false

<?PHP

$url = "https://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml";

// create curl resource 
$ch = curl_init();

//Now set some options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Download the given URL, and return output
$xml = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}

// Close the cURL resource, and free system resources
curl_close($ch);

//  Write the string $xml to a file, data.xml
if (file_put_contents ('data.xml', $xml) !== false) {
     echo 'Success!';
} else {
     echo 'Failed';
}
?>

The second, and proper fix. Set 3 options:

  1. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  2. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  3. curl_setopt($ch, CURLOPT_CAINFO, getcwd() . '\CAcert.crt');

The last thing you need to do is download the CA certificate.


<?PHP

$url = "https://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml";

// create curl resource 
$ch = curl_init();

//Now set some options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . '\CAcert.crt');


// Download the given URL, and return output
$xml = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}

// Close the cURL resource, and free system resources
curl_close($ch);

//  Write the string $xml to a file, data.xml
if (file_put_contents ('data.xml', $xml) !== false) {
     echo 'Success!';
} else {
     echo 'Failed';
}
?>