Home > Software design >  How to correct my PHP Code to use "file_get_contents" with "json_decode" which r
How to correct my PHP Code to use "file_get_contents" with "json_decode" which r

Time:08-03

I am trying to use the file_get_contents function on a JSON link with json_decode as you can see in the code below:

<?php
 $wiki_img_cat_api = "https://zh.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=original&titles=亞馬遜公司";
 $data_wikipedia_img_cat_api = json_decode(file_get_contents($wiki_img_cat_api), true);
 $data_wikipedia_img_cat_api = current($data_wikipedia_img_cat_api['query']['pages']);
 $firstWikipediaImage = isset($data_wikipedia_img_cat_api["original"]["source"]) ? $data_wikipedia_img_cat_api["original"]["source"] : "";
 echo $firstWikipediaImage;

But, I get the following error:

Warning: file_get_contents(https://zh.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=original&titles=亞馬遜公司): failed to open stream: HTTP request failed! HTTP/1.1 400 Invalid HTTP Request in C:\laragon\www\test3.php on line 205

Please help me to correct this above error.

CodePudding user response:

You need to URL encode the parameter values. The easiest way to do that is with the http_build_query function.

<?php
// Create an associative array of the URL parameters
$params = [
    'action'        => 'query',
    'format'        => 'json',
    'formatversion' => 2,
    'prop'          => 'pageimages|pageterms',
    'piprop'        => 'original',
    'titles'        => '亞馬遜公司'
];

$baseUrl     = 'https://zh.wikipedia.org/w/api.php';

// Build URL parameter string
$paramString = http_build_query($params);

// Append the parameter string to the base URL, make sure to include the ?
$apiRequestUrl = $baseUrl . '?' . $paramString;

// Everything else in your code works as expected
$data_wikipedia_img_cat_api = json_decode(file_get_contents($apiRequestUrl), true);

$data_wikipedia_img_cat_api = current($data_wikipedia_img_cat_api['query']['pages']);
$firstWikipediaImage        = isset($data_wikipedia_img_cat_api["original"]["source"]) ? $data_wikipedia_img_cat_api["original"]["source"] : "";
echo $firstWikipediaImage;

CodePudding user response:

I just tried adding this over all the url in the file_get_contents function like this:

$data_wikipedia_img_cat_api = json_decode(file_get_contents(urlencode($wiki_img_cat_api)), true);

But it returns me the following error:

Warning: file_get_contents(https://zh.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages%7Cpageterms&piprop=original&titles=亞馬遜公司): failed to open stream: No such file or directory in C:\laragon\www\test3.php on line 229

How to add urlencode only on the title ???

  •  Tags:  
  • php
  • Related