I am trying to do api integration with a news providing website through curl.I am able to retrieve the data but it is not in json format so it is difficult to display that data on my portal.
Below is the code which i am using.
Please someone help
curl.php
<?php
function file_get_contents_curl()
{
$url='https://newsapi.org/v2/top-headlines?'.
'country=us&'.
'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$content = false;
$headers = array('Content-Type:application/json');
if (function_exists('curl_init')) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
$content = curl_exec($curl);
curl_close($curl);
}
return $content;
}
$result=file_get_contents_curl();
echo $result;
?>
Below is the result which i am getting if i echo the response received from above code
{"status":"ok","totalResults":36,"articles":[{"source":{"id":null,"name":"Tmz.com"},"author":"TMZ Staff","title":"'90 Day Fiance' Colt Johnson Files for Divorce from Larissa After Fight and Arrest - TMZ","description":"Colt has filed for divorce from Larissa after the \"90 Day Fiance\" couple's bizarre fight and her arrest.","url":"https://www.tmz.com/2019/01/12/90-day-fiance-colt-johnson-files-divorce-larissa-dos-santos-lima-bloody-fight-arrest/","urlToImage":"https://images.tmz.com/2019/01/12/0112-larissa-johnson-colt-johnson-instagram-01-1200x630.jpg","publishedAt":"2019-01-12T20:55:00Z","content":null},{"source":{"id":null,"name":"Kstp.com"},"author":"The Associated Press","title":"Granddad: Wisconsin girl has no link to suspected kidnapper - KSTP","description":"The grandfather of a northwestern Wisconsin girl who authorities say was abducted during a home invasion that left her parents dead said Saturday that the family has no connection to the suspect and doesn't understand why he targeted her, deepening a mystery …","url":"https://kstp.com/news/granddad-wisconsin-girl-has-no-link-to-suspected-kidnapper-/5207911/","urlToImage":"https://kstp.com/kstpImages/repository/2019-01/800JakeThomasPattersonSuspectNewser2.jpeg","publishedAt":"2019-01-12T20:53:05Z","content":"Jayme had been missing for nearly three months Thursday when she approached a stranger near the small, isolated north woods town of Gordon and pleaded for help. Officers arrested 21-year-old Jake Thomas Patterson minutes later based on Jayme's description of … [+4624 chars]"},{"source":{"id":null,"name":"Vox.com"},"author":"Amanda Sakuma","title":"Megyn Kelly finalizes split with NBC - Vox.com","description":"The talk show host reportedly wanted to be the next Oprah. As she leaves NBC with a record of uncomfortable gaffes, it seems unlikely that will happen.","url":"https://www.vox.com/2019/1/12/18179908/megyn-kelly-nbc-split-oprah","urlToImage":"https://cdn.vox-cdn.com/thumbor/WiGGM5Fmnb_o5PN4zrXsPHnQRx4=/0x215:3000x1786/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/13321989/Kelly.jpg","publishedAt":"2019-01-12T19:57:29Z","content":"Megyn Kelly has officially split with NBC, taking the reminder of her $69 million contract with her, but leaving behind any aspiration of becoming the next queen of talk-show TV. The parties have resolved their differences, and Megyn Kelly is no longer an emp… [+3732 chars]"},
Use json_decode to turn the json you've received into an array!
$result = json_decode($result);
print_r($result);
Related
I'm trying to use the Ada language processor of OpenAi to summarize a piece of text.
When I try to use their playground, the function works and I get a summarization that makes sense and can be used by humans.
This is the cURL from the playground:
curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "text-ada-001",
"prompt": "Please write a one paragraph professional synopsis:\n\nSome text",
"temperature": 0,
"max_tokens": 60,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}'
When I take this cURL and transform it to PHP code, it stops working, or better said it works but it returns complete nonsense, nothing similar to the results from the playground.
PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$postFields = '{
"model": "text-ada-001",
"prompt": "Please write a one paragraph professional synopsis: ' . $text . '",
"temperature": 0,
"max_tokens": 500,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $api_key;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return $result;
Now, I tried to use both a json code like this, and to write a PHP array and convert it to json, same result. I have also tried to use a library but it also returned the same nonsense as before. I'm saying nonsense, because the text that it returns is not something that can be read and said, 'Hey, this is a proffesional synopsis'. I'm going to give an example of a sentence that I got in one of the iterations:
'It's not pretty and no I thought to myself, oh look IT'S NOT THAT REPUBLICAN kids would kno one of these things. OH IT'S A RESTRICTIOUS SCHOOL'.
I can assure you, there are no mentions of republicans or kids in the text that I'm processing.
My question is, am I doing something wrong? Does OpenAi work differently on their playground and in code?
Troubleshooting discrepancies between Playground vs. the OpenAI API:
Set the temperature parameter to 0. If the temperature parameter is set above 0, the model will likely produce different results each time - this is expected behavior.
Check that your prompt is exactly the same. Even slight differences, such as an extra space or newline character, can lead to different outputs.
Ensure you're using the same parameters in both cases. For example, the model parameter set to davinci and text-davinci-002 will produce different completions even with the same prompt, because text-davinci-002 is a newer and more capable instruction-following model.
Try to change the model from text-ada-001 to text-davinci-003 because it's the most capable GPT-3 model. It might be model related.
I'm new to StackOverflow, so I apologize if I'm not formatting this correctly. I'm using the GitHub API and my goal is to get a list of a user's repositories in a dropdown form that they can select from.
Let's say the repository list URL is https://api.github.com/users/MY_GITHUB_USERNAME/repos (The way I sat things up I can get the repo URL by doing $userdata->repos_url). When I use the following:
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, $userdata->repos_url);
curl_setopt($curl1, CURLOPT_HEADER, 0);
curl_setopt($curl1, CURLOPT_HTTPHEADER, array(
'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth'
));
curl_setopt($curl1,CURLOPT_USERAGENT,'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth');
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl1, CURLOPT_SSL_VERIFYHOST, 0);
$cont1 = curl_exec($curl1);
curl_close($cont1);
echo $cont1;
It responds with the following:
[
{
(information I don't need)
"full_name": "github-username/this-is-what-i-want",
(information I don't need)
}
]
I only have one repository at the moment. What I want to do is make a code that echos only the full_name and if there's more than one array echo each one. (All arrays will have full_name.)
Does anyone know how I could do this?
Decode it to an array, then loop through the arrays until you get to what you want:
$data=json_decode($cont1, true); <~~~ tells php to decode the JSON into an array
$results=$data['FirstArray']['SecondArray']['NumResultsReturned']; <~~ most JSON's have a value showing how many arrays got sent back to you in the results. You didn't give a true data example as a reply, so can't give exacts on these fields for you.
I am developing a php application where user input a link to any public GitHub repository and output will be
(i) Total number of open issues
(ii) Number of open issues that were opened in the last 24 hours
(iii) Number of open issues that were opened more than 24 hours ago but less than 7 days ago
(iv) Number of open issues that were opened more than 7 days ago
Code for printing the (i) Total number of open issues is given below using the github api and php curl and it is working fine.
But I have no idea how to print the other above three points (ii),(iii) and (iv).
Any help regarding this will be appreciated. Thanks in advance.
<?php
//Test url
$url = "https://api.github.com/repos/anandkgpt03/test";
//Initiate curl
$ch = curl_init();
//Set the url
curl_setopt($ch, CURLOPT_URL,$url);
//Set the User Agent as username
curl_setopt($ch, CURLOPT_USERAGENT, "anandkgpt03");
//Accept the response as json
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: application/json'));
//Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
//Decode the json in associative array
$new_result=json_decode($result,true);
echo "Total Number of Open Issues:".$new_result["open_issues_count"];
?>
You can get what you want by using the GitHub API.
Follow these steps:
Visit the issues url with the option state open:
https://api.github.com/repos/{name}/support/issues?q=state:open.
In the results (in JSON format) look for the created_at timestamp.
Compare the aforementioned values with the current timestamp and sort these outputs by using any datetime function.
Hope this helps!
I have used since paramater available in GitHub API that return only issues updated at or after this time that helps in getting number of open issues opened after any time.
This url can be helpful to read more about it: https://developer.github.com/v3/issues/
Below is the proper working code of my question.
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="url" placeholder="Full URL of GitHub repository" size="60">
<input type="submit" name="submitButton">
</form>
</body>
</html>
<?php
if(isset($_POST['submitButton']))
{
//Example-> https://github.com/Shippable/support/issues
$input_url = $_POST['url'];
//Break the input url in array format
$input_url_array = explode('/',$input_url);
//Validate the input url
if(strcmp($input_url_array[0],"https:")||strcmp($input_url_array[1],"")||strcmp($input_url_array[2],"github.com")||empty($input_url_array[3])||empty($input_url_array[4]))
{
die("</br>Invalid Url !!! Url should be in format <b>https://github.com/{org_name or username}/{repo_name}/</b><br>");
}
//url for the github Api, $input_url_array[3] contain organisation or username, put_url_array[3] contain repository name
$url = "https://api.github.com/repos/".$input_url_array[3]."/".$input_url_array[4];
//call the function and receive the result in associative array format
$result = curlRequestOnGitApi($url);
//Get total no of open issues using the $result array
$total_open_issues = $result["open_issues_count"];
echo "<br>Total Open Issues:<b>".$total_open_issues."</b><br>";
//Date and Time 1 day or 24 hours ago in ISO 8601 Format
$time_last24hr = date('Y-m-d\TH:i:s.Z\Z', strtotime('-1 day', time()));
//url for the github Api with since parameter equal to time of last 24 hrs that return only issues updated at or after this time
$url = "https://api.github.com/repos/".$input_url_array[3]."/".$input_url_array[4]."/issues?since=".$time_last24hr;
//call the function and receive the result in associative array format
$result = curlRequestOnGitApi($url);
//Get no of open issues that were opened in last 24 hours
$issues_last24hr = count($result);
echo "Number of open issues that were opened in the last 24 hours:<b>".$issues_last24hr."</b><br>";
//Date and Time 1 day or 24 hours ago in ISO 8601 Format
$time_7daysago = date('Y-m-d\TH:i:s.Z\Z', strtotime('-7 day', time()));
//url for the github Api with since parameter equal to time of 7 days ago that return only issues updated at or after this time
$url = "https://api.github.com/repos/".$input_url_array[3]."/".$input_url_array[4]."/issues?since=".$time_7daysago;
//call the function and receive the result in associative array format
$result = curlRequestOnGitApi($url);
//Get no of open issues that were opened in 7 days ago
$issues_last7days = count($result);
echo "Number of open issues that were opened more than 24 hours ago but less than 7 days ago:<b>".($issues_last7days-$issues_last24hr)."</b><br>";
echo "Number of open issues that were opened more than 7 days ago:<b>".($total_open_issues-$issues_last7days)."</b><br>";
}
function curlRequestOnGitApi($url)
{
$ch = curl_init();
//Set the url
curl_setopt($ch, CURLOPT_URL,$url);
//Set the User Agent as username
curl_setopt($ch, CURLOPT_USERAGENT, "anyusername");
//Accept the response as json
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: application/json'));
//Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
//Decode the json in array
$new_result=json_decode($result,true);
//Return array
return $new_result;
}
?>
I have implemented the EAN hotel search API using XML and PHP. And I have the following issue when searching and listing hotels.
Search details
City - Soho
Country - GB
Arrival - Aug 1, 2013
Departure - Aug 2, 2013
Rooms - 1 room with 2 adults
Results in TravelNow site
http://www.travelnow.com/templates/331656/hotels/list?lang=en¤cy=GBP&secureUrlFromDataBridge=https%3A%2F%2Fwww.travelnow.com&requestVersion=V2&destination=&standardCheckin=8%2F1%2F2013&standardCheckout=8%2F2%2F2013&checkin=8%2F1%2F13& amp;checkout=8%2F2%2F13&rating=0&targetId=AREA-d5cfc783-9e42-4440-9200-0bd17397c37f%7Clandmarks&roomsCount=1&rooms[0].adultsCount=2&rooms[0].childrenCount=0&filter.sortedBy=our_rec&filter.hotelName=&filter.lowPrice=0&filter.travelerOpinion=0&filter.breakfastIncluded=false&subscriptionInfo.termsConditionAgreement=false&subscriptionInfo.wantNews=false&subscriptionInfo.wantNewsletters=false&tab=list
In TravelNow site, we searched for Soho, London, United Kingdom as shown in the above URL
Request sent
http://api.ean.com/ean-services/rs/hotel/v3/list?currencyCode=GBP&minorRev=99&apiKey=XXXXXXXXXXXXXXXXXXXXXXXX&locale=en_US&cid=XXXXXXXX&sort=OVERALL_VALUE&xml=<HotelListRequest><city>Soho<%2Fcity><countryCode>GB<%2FcountryCode><arrivalDate>08%2F01%2F2013<%2FarrivalDat e><departureDate>08%2F02%2F2013<%2FdepartureDate><numberOfResults>25<%2FnumberOfResults><supplierType>E%7CV<%2FsupplierType><supplierCacheTolerance>MED_ENHANCED<%2FsupplierCacheTolerance><RoomGroup><Room><numberOfAdults>2<%2FnumberOfAdults><%2FRoom><%2FRoomGroup><%2FHotelListRequest>
Response received
<ns2:HotelListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/">
<EanWsError>
<itineraryId>-1</itineraryId>
<handling>UNKNOWN</handling>
<category>EXCEPTION</category>
<exceptionConditionId>-1</exceptionConditionId>
<presentationMessage>No Results Available</presentationMessage>
<verboseMessage>Result was null</verboseMessage>
<ServerInfo serverTime="05:45:17.821-0500" timestamp="1375181117" instance="54"/>
</EanWsError>
<customerSessionId>0ABAAA36-B023-AF91-4022-F2DA5EE95A74</customerSessionId>
</ns2:HotelListResponse>
I also searched with city string "Soho, London, United Kingdom" given for city/destinationString didn't list any hotel. We used API tester http://devhub.ean.com/apitester/index.html too and received the same results.
This search mostly says no results for many cities in London. We tried "destinationString" based search shown in http://developer.ean.com/docs/read/hotel_list/examples/XML_Alternatives but didn't work either. How do we need to pass the destination/city? Even when it shows hotels they are not in/around the given city.
Let us know how to implement the above request to work properly to list the hotels in a given city. This works only for a few cities we have listed in the search. Shown below is a list of exact city names in London we use to pass in the request, inside the block. If below city names are incorrect, then how do they need to be corrected?
Bayswater-Paddington,
Belgravia,
Bloomsbury-Soho,
Canary Wharf-Docklands,
Camden Town,
Chelsea,
Chelsea-Knightsbridge,
City of Westminster,
Chinatown,
East End,
Fulham,
Greenwich,
Holborn,
Hammersmith,
Hampstead,
Hampstead-Camden Town,
Hounslow,
Islington,
Knightsbridge,
Kensington,
Lambeth,
London,
London area,
Mayfair,
Mayfair-Marylebone,
Marylebone,
Pimlico,
St. Pancras - Islington,
Soho,
Southwark-Waterloo
Please help with a REST/XML request string that works for the above city/cities.
I haven't accepted any of the current answers but are looking for more correct answers that rings a bell.
I am using REST method for get hotel list
My code is given below
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?minorRev=14
&cid=55505
&apiKey=p9ycn9cxb2zp3k3gfvbf5aym
&customerUserAgent=&customerIpAddress=
&locale=en_US
¤cyCode=USD
&city=Lasvegas
&stateProvinceCode=NV
&countryCode=US
&supplierCacheTolerance=MED
&arrivalDate=08/25/2013
&departureDate=08/27/2013
&room1=2
&numberOfResults=25
&supplierCacheTolerance=MED_ENHANCED';
$header[] = "Accept: application/json";
$header[] = "Accept-Encoding: gzip";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = json_decode(curl_exec($ch));
$rt = curl_getinfo($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
You want more details.
See this links
You have to use geoSearch tab given at api tester by ean:
http://devhub.ean.com/apitester/index.html
after that you have to insert destination string in that and fetch the city name according to the responce.
Here is the sample code how you have to do this:
$destination="soho";//YOUR Destination string
$Geosearch='https://api.eancdn.com/ean-services/rs/hotel/v3/geoSearch?cid=50555&minorRev=99&apiKey=**XXXXX(your_api_key)**&locale=en_US¤cyCode=USD&xml=%3CLocationInfoRequest%3E%0A%20%20%20%20%3Clocale%3Een_US%3C%2Flocale%3E%0A%20%20%20%20%3CdestinationString%3E';
$Geosearch.=$destination;
$Geosearch.='%3C%2FdestinationString%3E%0A%3C%2FLocationInfoRequest%3E';
$locate = json_decode(file_get_contents($Geosearch),true);
$citynames=$locate['LocationInfoResponse']['LocationInfos']['LocationInfo'];
$citysearched=$citynames['city'];
Now you have to use hotel list url and concatinate $citysearched value instead of your destination string.
You may using file_get_contents
below are the code
$request = "http://dev.api.ean.com/ean-services/rs/hotel/v3/list";
$minorRev = "20";
$cid = "55505";
$api = "p9ycn9cxb2zp3k3gfvbf5aym";
//room available
$response = file_get_contents($request . '?minorRev=' . $minorRev . '&cid=' . $cid . '&apiKey=' . $api . '&locale=en_US¤cyCode=MYR&hotelId='. $hotel_id . '&arrivalDate=' . $arrivalDate . '&departureDate=' . $departureDate . $room . '&includeDetails=true&includeRoomImages=true&options=HOTEL_DETAILS,ROOM_TYPES,ROOM_AMENITIES,HOTEL_IMAGES');
$result = json_decode($response, false);
By the way the api link should be http://dev.api.ean.com/
I got same issue, Finally found issue with whitespace (\n \r). You can remove whitespace using below method.
function prepare_xml($xml=""){
$xml = preg_replace('/\s+/', ' ',$xml);
$xml = str_replace("> <","><",$xml);
return $xml;
}
I am trying to get a list of results from Freebase. I have an array of MIDs. Can someone explain how I would structure the query and pass it to the API in PHP?
I'm new to MQL - I can't even seem to get the example to work:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/writer/film'=>array());
$jsonquerystr = json_encode($simplequery);
// The Freebase API requires a query envelope (which allows you to run multiple queries simultaneously) so we need to wrap our original, simplequery structure in two more arrays before we can pass it to the API:
$queryarray = array('q1'=>array('query'=>$simplequery));
$jsonquerystr = json_encode($queryarray);
// To send the JSON formatted MQL query to the Freebase API use cURL:
#run the query
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
// Decoding the JSON structure back into arrays is performed using json_decode as in:
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array
// Iterating over the pieces of the resultarray containing films gives us the films Philip K. Dick wrote:
$filmarray = $resultarray["q1"]["result"]["/film/writer/film"];
foreach($filmarray as $film){
print "$film<br>";
}
You're doing everything right. If you weren't, you'd be getting back error messages in your JSON result.
I think what's happened is that the data on Philip K. Dick has been updated to identify him not as the "writer" of films, but as a "film_story_contributor". (He didn't, after all, actually write any of the screenplays.)
Change your simplequery from:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/writer/film'=>array());
To:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/film_story_contributor/film_story_credits'=>array());
You actually can use the Freebase website to drill down into topics to dig up this information, but it's not that easy to find. On the basic Philip K. Dick page (http://www.freebase.com/view/en/philip_k_dick), click the "Edit and Show details" button at the bottom.
The "edit" page (http://www.freebase.com/edit/topic/en/philip_k_dick) shows the Types associated with this topic. The list includes "Film story contributor" but not "writer". Within the Film story contributor block on this page, there's a "detail view" link (http://www.freebase.com/view/en/philip_k_dick/-/film/film_story_contributor/film_story_credits). This is, essentially, what you're trying to replicate with your PHP code.
A similar drill-down on an actual film writer (e.g., Steve Martin), gets you to a property called /film/writer/film (http://www.freebase.com/view/en/steve_martin/-/film/writer/film).
Multiple Queries
You don't say exactly what you're trying to do with an array of MIDs, but firing multiple queries is as simple as adding a q2, q3, etc., all inside the $queryarray. The answers will come back inside the same structure - you can pull them out just like you pull out the q1 data. If you print out your jsonquerystr and jsonresultstr you'll see what's going on.
Modified a bit to include answer into question, as this helped me I've upvoted each, just thought I would provide a more "compleat" answer, as it were:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/film_story_contributor/film_story_credits'=>array());
$jsonquerystr = json_encode($simplequery);
// The Freebase API requires a query envelope (which allows you to run multiple queries simultaneously) so we need to wrap our original, simplequery structure in two more arrays before we can pass it to the API:
$queryarray = array('q1'=>array('query'=>$simplequery));
$jsonquerystr = json_encode($queryarray);
// To send the JSON formatted MQL query to the Freebase API use cURL:
#run the query
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
// Decoding the JSON structure back into arrays is performed using json_decode as in:
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an associative array
// Iterating over the pieces of the resultarray containing films gives us the films Philip K. Dick wrote:
if($resultarray['code'] == '/api/status/ok'){
$films = $resultarray['q1']['result']['/film/film_story_contributor/film_story_credits'];
foreach ($films as $film){
print "$film</br>";
}
}