John Davidson

php - how get json data from wordpress api?

0 comments
Message:


I created a REST API with wordpress to get some json data and this is the link is return all the data for me :
https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go


and from another domain i have another website made with wordpress also i create PHP script to get those data :


function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}

try {
$json_data = file_contents("https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go");
var_dump($json_data);
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}

and i got this error instead :



Error: Cannot access
'https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go'
to read contents.



some help please


Thanks



My Answer:
It looks like the issue might be related to the SSL certificate on the server hosting the WordPress site. You can try adding the following code to your PHP script to ignore SSL verification:

php
stream_context_set_default(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
)
);


Add this code before making the `file_get_contents` call. This will disable SSL verification and allow the script to access the data from the WordPress API.

If this doesn't work, you can also try using cURL to make the request instead of `file_get_contents`. Here's an example:

php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json_data = curl_exec($ch);
curl_close($ch);

var_dump($json_data);


This code uses cURL to make the request, which can sometimes be more reliable than `file_get_contents`. Give these solutions a try and see if they help resolve the issue.

Rate this post

4 of 5 based on 7304 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us