PHP file_get_contents failed to open multiple stream - php

I am working on a php script that is supposed to use the file_get_contents function.
When I use it in my script just once it works fantastic and I don't get any error but if I implement it more then once I get the following error:
"https://engine.sighten.io/api/ops/download_from_remote/1644d83f-675b-42f9-a8cc-b2cb63d9c705/):
failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST".
Here are the details:
The webhook I receive is something like this:
{
"owned_by_user":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"date_completed":"None",
"date_created":"2017-08-16T12:47:17.700198+00:00",
"date_started":"None",
"milestone":{
"link":"/api/solar/milestone/eb8fad9a-47cf-448a-920d-9a4d35b3ea39",
"uuid":"eb8fad9a-47cf-448a-920d-9a4d35b3ea39",
"natural_id":"API TEST 1 Test Ignore//Cash // Sales Requirements"
},
"natural_id":"Installation Agreement",
"status":"SIGN",
"created_by":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"documents":[
{
"owned_by_user":{
},
"date_created":"2017-08-16T12:49:49.245223+00:00",
"created_by":{
},
"download_url":"/api/ops/download_from_remote/69c6a394-310a-4300-a18b-7544edfa28a9/",
"modified_by":{
},
"uuid":"69c6a394-310a-4300-a18b-7544edfa28a9",
"description":"Sun Us Solar Agreement v3.pdf",
"natural_id":"Sun Us Solar Agreement v3.pdf",
"date_updated":"2017-08-16T12:49:49.245248+00:00",
"owned_by_organization":{
},
"remote_host":"AMZ",
"name":"Sun Us Solar Agreement v3.pdf",
"merged_doc":true
},
{
"owned_by_user":{
},
"date_created":"2017-08-16T12:49:54.873908+00:00",
"created_by":{
},
"download_url":"/api/ops/download_from_remote/7737b88f-0dec-4917-bf73-aa52e3c5e6ab/",
"modified_by":{
},
"uuid":"7737b88f-0dec-4917-bf73-aa52e3c5e6ab",
"description":"Sun Us Solar Agreement v3.pdf",
"natural_id":"Sun Us Solar Agreement v3.pdf",
"date_updated":"2017-08-16T12:49:54.873936+00:00",
"owned_by_organization":{
},
"remote_host":"AMZ",
"name":"Sun Us Solar Agreement v3.pdf",
"merged_doc":true
},
{
"owned_by_user":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"date_created":"2017-08-16T13:03:42.708770+00:00",
"created_by":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"download_url":"/api/ops/download_from_remote/1644d83f-675b-42f9-a8cc-b2cb63d9c705/",
"modified_by":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"uuid":"1644d83f-675b-42f9-a8cc-b2cb63d9c705",
"description":"Harry Potter and the Sorcerer's Stone.pdf",
"natural_id":"Harry Potter and the Sorcerer's Stone.pdf",
"date_updated":"2017-08-16T13:03:42.708799+00:00",
"owned_by_organization":{
"link":"",
"uuid":"e62239df-7f3a-4ead-b4cd-500541f8b094",
"natural_id":"Sunus Solar"
},
"remote_host":"AMZ",
"name":"Harry Potter and the Sorcerer's Stone.pdf",
"merged_doc":true
}
],
"modified_by":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"uuid":"411143d0-ecde-429d-943f-d4f22f12c87c",
"type":"DOC",
"assigned_to":{
"link":"",
"uuid":"ec5aec48-621e-4cd6-a029-d5da1a9a18d5",
"natural_id":"jbantock#catalystgroupdevelopment.com"
},
"date_updated":"2017-08-16 13:03:42.768407+00:00",
"date_approved":"None",
"owned_by_organization":{
"link":"",
"uuid":"e62239df-7f3a-4ead-b4cd-500541f8b094",
"natural_id":"Sunus Solar"
},
"comments":[
],
"site_id":"ac396b97-b22a-4914-9a0f-dbbda61116eb",
"name":"Installation Agreement" }
The php code part, which makes the download:
foreach($documents as &$document) {
$downloadlink = $document['download_url'];
$downloadname = $document['name'];
$remote_url = 'https://engine.sighten.io' . $downloadlink;
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Token cd048c7b0a127d876e5481ccbd0beb1566bebea2"
)
);
$context = stream_context_create($opts);
$file = file_get_contents($remote_url, false, $context);
$download = file_put_contents($downloadname, $file);
}
As you can see the json file contains 2 links/files. The script work well in case of the first file, I can download on my server, but in case of second file I get the above mentioned error. I have checked and the $remote_url variable contains the correct URL of the files.
CLARIFICATION:
When I execute the script I see the following
Files
The problem is that the second file has no content. Please note, that I have executed the script once again, with other files so the json in this case was the following:
{"date_created": "2017-08-16T15:10:19.327922+00:00", "status": "SIGN", "owned_by_user": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "documents": [{"download_url": "/api/ops/download_from_remote/b608171b-4cd3-4b2a-bef0-19635b00ed52/", "merged_doc": true, "owned_by_user": {}, "date_updated": "2017-08-16T15:10:45.039007+00:00", "uuid": "b608171b-4cd3-4b2a-bef0-19635b00ed52", "remote_host": "AMZ", "description": "Sun Us Solar Agreement v3.pdf", "created_by": {}, "date_created": "2017-08-16T15:10:45.038979+00:00", "modified_by": {}, "owned_by_organization": {}, "name": "Sun Us Solar Agreement v3.pdf", "natural_id": "Sun Us Solar Agreement v3.pdf"}, {"download_url": "/api/ops/download_from_remote/049957a5-1340-4e47-bfa2-3e4832d8b88f/", "merged_doc": true, "owned_by_user": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "date_updated": "2017-08-16T15:17:21.529021+00:00", "uuid": "049957a5-1340-4e47-bfa2-3e4832d8b88f", "remote_host": "AMZ", "description": "Harry Potter and the Sorcerer's Stone.pdf", "created_by": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "date_created": "2017-08-16T15:17:21.528992+00:00", "modified_by": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "owned_by_organization": {"link": "", "natural_id": "Sunus Solar", "uuid": "e62239df-7f3a-4ead-b4cd-500541f8b094"}, "name": "Harry Potter and the Sorcerer's Stone.pdf", "natural_id": "Harry Potter and the Sorcerer's Stone.pdf"}], "date_updated": "2017-08-16 15:17:21.584150+00:00", "date_approved": "None", "modified_by": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "type": "DOC", "created_by": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "comments": [], "uuid": "0f94a08f-4f06-444c-babe-f32ed059a88f", "assigned_to": {"link": "", "natural_id": "jbantock#catalystgroupdevelopment.com", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5"}, "owned_by_organization": {"link": "", "natural_id": "Sunus Solar", "uuid": "e62239df-7f3a-4ead-b4cd-500541f8b094"}, "date_started": "None", "name": "Installation Agreement", "date_completed": "None", "natural_id": "Installation Agreement", "milestone": {"link": "/api/solar/milestone/1b599fcd-448f-4444-a636-1ae931f25461", "natural_id": "API TEST 1 Test Ignore//Cash // Sales Requirements", "uuid": "1b599fcd-448f-4444-a636-1ae931f25461"}, "site_id": "c2504124-55e4-43b5-9a0c-370ec494d887"}

i can't access your request link because i don't have an API key,
When I use it in my script just once it works fantastic and I don't get any error but if I implement it more then once I get an error
Are you sure you got one that doesn't have API limitations (like one request a second)?
file_get_contents and file_put_content sometimes say synchronously they finished their jobs when in fact the hard disk is still writing content, i had a similar issue and i figured out it worked if i called the function twice but with a 4s sleep inbetween
Hope this will help.

This script is working for me. It does not save to file, as discussion above revealed TS cannot read the 3rd file and so it would not be the problem here
at the end of the foreach-loop some vars are dumped to screen for debugging purposes.
<?php
error_reporting(E_ALL); ini_set('display_errors', true);
$d = '{"owned_by_user": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "date_completed": "None", "date_created": "2017-08-16T12:47:17.700198+00:00", "date_started": "None", "milestone": {"link": "/api/solar/milestone/eb8fad9a-47cf-448a-920d-9a4d35b3ea39", "uuid": "eb8fad9a-47cf-448a-920d-9a4d35b3ea39", "natural_id": "API TEST 1 Test Ignore//Cash // Sales Requirements"}, "natural_id": "Installation Agreement", "status": "SIGN", "created_by": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "documents": [{"owned_by_user": {}, "date_created": "2017-08-16T12:49:49.245223+00:00", "created_by": {}, "download_url": "/api/ops/download_from_remote/69c6a394-310a-4300-a18b-7544edfa28a9/", "modified_by": {}, "uuid": "69c6a394-310a-4300-a18b-7544edfa28a9", "description": "Sun Us Solar Agreement v3.pdf", "natural_id": "Sun Us Solar Agreement v3.pdf", "date_updated": "2017-08-16T12:49:49.245248+00:00", "owned_by_organization": {}, "remote_host": "AMZ", "name": "Sun Us Solar Agreement v3.pdf", "merged_doc": true}, {"owned_by_user": {}, "date_created": "2017-08-16T12:49:54.873908+00:00", "created_by": {}, "download_url": "/api/ops/download_from_remote/7737b88f-0dec-4917-bf73-aa52e3c5e6ab/", "modified_by": {}, "uuid": "7737b88f-0dec-4917-bf73-aa52e3c5e6ab", "description": "Sun Us Solar Agreement v3.pdf", "natural_id": "Sun Us Solar Agreement v3.pdf", "date_updated": "2017-08-16T12:49:54.873936+00:00", "owned_by_organization": {}, "remote_host": "AMZ", "name": "Sun Us Solar Agreement v3.pdf", "merged_doc": true}, {"owned_by_user": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "date_created": "2017-08-16T13:03:42.708770+00:00", "created_by": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "download_url":"/api/ops/download_from_remote/1644d83f-675b-42f9-a8cc-b2cb63d9c705/", "modified_by": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "uuid": "1644d83f-675b-42f9-a8cc-b2cb63d9c705", "description": "Harry Potter and the Sorcerer\'s Stone.pdf", "natural_id": "Harry Potter and the Sorcerer\'s Stone.pdf", "date_updated": "2017-08-16T13:03:42.708799+00:00", "owned_by_organization": {"link": "", "uuid": "e62239df-7f3a-4ead-b4cd-500541f8b094", "natural_id": "Sunus Solar"}, "remote_host": "AMZ", "name": "Harry Potter and the Sorcerer\'s Stone.pdf", "merged_doc": true}], "modified_by": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "uuid": "411143d0-ecde-429d-943f-d4f22f12c87c", "type": "DOC", "assigned_to": {"link": "", "uuid": "ec5aec48-621e-4cd6-a029-d5da1a9a18d5", "natural_id": "jbantock#catalystgroupdevelopment.com"}, "date_updated": "2017-08-16 13:03:42.768407+00:00", "date_approved": "None", "owned_by_organization": {"link": "", "uuid": "e62239df-7f3a-4ead-b4cd-500541f8b094", "natural_id": "Sunus Solar"}, "comments": [], "site_id": "ac396b97-b22a-4914-9a0f-dbbda61116eb", "name": "Installation Agreement"}';
$documents = json_decode($d);
$documents = $documents->documents;
foreach($documents as $document) {
$downloadlink = $document->download_url;
$downloadname = $document->name;
$remote_url = 'https://engine.sighten.io' . $downloadlink;
$opts = array('http' => array('method' => "GET", 'header' => "Authorization: Token cd048c7b0a127d876e5481ccbd0beb1566bebea2"
));
$context = stream_context_create($opts);
$file = file_get_contents($remote_url, false, $context);
$size = strlen($file);
if(1) {
echo 'on line: ' . __LINE__ . ' in file ' . __FILE__;
printf('<pre>%s</pre>', print_r($document->download_url, 1));
printf('<pre>%s</pre>', print_r($downloadname, 1));
printf('<pre>%s</pre>', print_r($size, 1));
}
} ?>
Are you sure you send the Auth code along in your real script?

Related

How to get a particular string from and api response?

I have been on a little project of mine now i want to find imdb_id using tmdb_id so for that I have been trying to use the API.
https://api.themoviedb.org/3/tv/67026?api_key=myapikey&append_to_response=external_ids
which brings up the results like this
{
"backdrop_path": "/hcFbIbDzsB9aSSw9VkSGFEl5sGO.jpg",
"created_by": [{
"id": 230174,
"credit_id": "577eb8e5c3a368694a0027ac",
"name": "David Guggenheim",
"gender": 2,
"profile_path": "/hqSydaadHO6EsBIn3BQEzzfxNUY.jpg"
}],
"episode_run_time": [42],
"first_air_date": "2016-09-21",
"genres": [{
"id": 18,
"name": "Drama"
}, {
"id": 10768,
"name": "War & Politics"
}],
"homepage": "https://www.netflix.com/title/80113647",
"id": 67026,
"in_production": false,
"languages": ["en"],
"last_air_date": "2019-06-07",
"last_episode_to_air": {
"air_date": "2019-06-07",
"episode_number": 10,
"id": 1809432,
"name": "#truthorconsequences",
"overview": "On election day, Kirkman turns to his therapist to assuage his conscience about the events -- and his own decisions -- of the momentous prior 36 hours.",
"production_code": "",
"season_number": 3,
"show_id": 67026,
"still_path": "/cpy3uV100RyZuvJN535JLTrj4Nz.jpg",
"vote_average": 7.0,
"vote_count": 1
},
"name": "Designated Survivor",
"next_episode_to_air": null,
"networks": [{
"name": "ABC",
"id": 2,
"logo_path": "/ndAvF4JLsliGreX87jAc9GdjmJY.png",
"origin_country": "US"
}, {
"name": "Netflix",
"id": 213,
"logo_path": "/wwemzKWzjKYJFfCeiB57q3r4Bcm.png",
"origin_country": ""
}],
"number_of_episodes": 53,
"number_of_seasons": 3,
"origin_country": ["US"],
"original_language": "en",
"original_name": "Designated Survivor",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"popularity": 30.031,
"poster_path": "/5R125JAIh1N38pzHp2dRsBpOVNY.jpg",
"production_companies": [{
"id": 28788,
"logo_path": null,
"name": "Genre Films",
"origin_country": "US"
}, {
"id": 19366,
"logo_path": "/vOH8dyQhLK01pg5fYkgiS31jlFm.png",
"name": "ABC Studios",
"origin_country": "US"
}, {
"id": 78984,
"logo_path": null,
"name": "Entertainment 360",
"origin_country": "US"
}],
"seasons": [{
"air_date": "2016-09-20",
"episode_count": 21,
"id": 78328,
"name": "Season 1",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"poster_path": "/1QHlD6z9FnXuuTDVLJnjrtLfVyq.jpg",
"season_number": 1
}, {
"air_date": "2017-09-27",
"episode_count": 22,
"id": 91130,
"name": "Season 2",
"overview": "",
"poster_path": "/z4hdj8cYyqCO9lVBOGm6YZsnMho.jpg",
"season_number": 2
}, {
"air_date": "2019-06-07",
"episode_count": 10,
"id": 122914,
"name": "Season 3",
"overview": "",
"poster_path": "/wn310FWQhjjpHbqsMRBcXr28EHc.jpg",
"season_number": 3
}],
"status": "Canceled",
"type": "Scripted",
"vote_average": 7.2,
"vote_count": 408,
"external_ids": {
"imdb_id": "tt5296406",
"freebase_mid": null,
"freebase_id": null,
"tvdb_id": 311876,
"tvrage_id": 51115,
"facebook_id": "DesignatedSurvivor",
"instagram_id": "designatedsurvivor",
"twitter_id": "DesignatedNFLX"
}
}
So now if I want to get just the IMDb_ID form the external_ids then what code should i use in PHP and store it in a variable.
Thank you very much in advance.
use the json_decode method to treat JSON like a PHP object
$data = 'your JSON object';//raw data as string in $data
$decoded = json_decode($data);//decoded data as PHP object
echo $decoded->external_ids->imdb_id; //access any property you like
hope this helps!!!

Having trouble displaying Multiple Home Card Display on Alexa in Single Response

I have a application running on ALEXA (Amazon Echo). I'm implementing Home card display with images. When for a particular call if the response has only one card. It shows perfectly fine. Screenshot attached
"Response": {
"version" : "1.0",
"sessionAttributes": {
"UserCityId": "1",
"UserCity": "London",
"latitude": "51.50735090",
"longitude": "-0.12775830",
"categoryID": "900",
"company_id": "1154916",
"first_name": "User FName",
"yes_no_for": "",
"cat_start_limit": "0",
"categoryName": "music",
"total_cat_events": "2178",
"show_rec": "5"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "This is what alexa speaks out"
},
"card": {
"type": "Standard",
"title": "Music events in London",
"text": "The speech passed to alexa",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know events for music ,sports, or something else. Please select one category"
}
},
"shouldEndSession": false
}
}
The above code works
The problem is listed below :
But if the same response has array of cards (multiple cards), alexa fails giving an error.
"Response": {
"version": "1.0",
"sessionAttributes": {
"UserCityId": "1",
"UserCity": "London",
"latitude": "51.50735090",
"longitude": "-0.12775830",
"categoryID": "900",
"customer_id": "1154916",
"first_name": "UserFNAME",
"yes_no_for": "",
"cat_start_limit": "0",
"categoryName": "music",
"total_cat_events": "2178",
"show_rec": "5"
},
"response" : {
"outputSpeech" : {
"type": "PlainText",
"text": "5th. Baba Yaga's Hut Presents Jambinai, at Corsica Studios, on Monday, May 16th , 7 30 pm"
},
"card": [{
"type": "Standard",
"title": "Music events in London",
"text": "1. Dove Jones Blues Jam!, at Phoenix Artist Club, on Monday, May 16th , 7pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "2. The Hillbilly Moon Explosion, at The Borderline, on Monday, May 16th, 7pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "3. Sian Evans Of Kosheen, at 100 Club, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "4. Rinocerose, at The Water Rats, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "5. Baba Yaga's Hut Presents Jambinai, at Corsica Studios, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}],
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know events for music ,sports, or something else. Please select one category"
}
},
"shouldEndSession" : false
}
}
The above code doesn't work.
Here is the thing that I'm trying to convert : Please see the screenshot
For events in london call I get list of 5 events in single card. To each event I want to assign image and create its card.
Can anyone help with the approach and figure out what is the problem using multiple card in JSON response.
Is it that alexa only support single card in response ?
The card attribute on the response takes an object not an array.
Here is the example that Amazon uses on their site:
{
"version": "string",
"sessionAttributes": {
"string": object
},
"response": {
"outputSpeech": {
"type": "string",
"text": "string",
"ssml": "string"
},
"card": {
"type": "string",
"title": "string",
"content": "string",
"text": "string",
"image": {
"smallImageUrl": "string",
"largeImageUrl": "string"
}
},
"reprompt": {
"outputSpeech": {
"type": "string",
"text": "string",
"ssml": "string"
}
},
"shouldEndSession": boolean
}
}
If you wanted to try and make multiple cards, you could try sending multiple responses, but I am not sure that that would work either.
I think your best option is to consider a different interaction with the user for your problem then presenting multiple cards.

Accessing a JSON Using the NYT API

I'm currently using the NYT News API to search for articles. I'm trying to get the Article Name, and URL from the JSON. How do I do this for each entry in the JSON?
$curl = curl_init();
$call = 'http://api.nytimes.com/svc/search/v2/articlesearch.json? q=Denmark&begin_date=20040112&end_date=20041212&sort=oldest&api-key=mykey';
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
echo $resp = curl_exec($curl);
curl_close($curl);
//Decode Json
$y = json_decode($resp,true);
It returns a large JSON, I'm interested in retrieving the weburl, and headline field. I've tried:
$url = $y['response']['docs']['web_url']
and
$headline = $y['response']['docs']['headline']
but with no success. Any thoughts?
I also need all the entries that have a web_url and headline in the JSON.
A single article entry from the JSON response:
{
"response": {
"meta": {
"hits": 291,
"time": 102,
"offset": 0
},
"docs": [{
"web_url": "http://www.nytimes.com/2005/01/14/arts/design/14anti.html",
"snippet": "On Wednesday, Christie's New York is having what it claims is the first-ever auction devoted solely to Georg Jensen silver, with some 800 objects.",
"lead_paragraph": "Georg Jensen silver from Denmark has a tactile quality all its own, probably because it is handmade. It gets only better with age. Michael von Essen, the founder and curator of the Georg Jensen Museum in Copenhagen, tried to explain its appeal: ''Once you have touched pieces of Jensen, you want to have them. The silver has a warmth to it, whether the style is 1900, Art Deco or modern.'' Last year, the company Georg Jensen founded celebrated its 100th anniversary. Jensen, who was not a gifted businessman, would probably have been surprised.",
"abstract": "Wendy Moonan Antiques column profiles Danish silversmith Georg Jensen, whose company celebrated its centennial last year; Michael von Essen, founder and curator of Georg Jensen Museum in Copenhagen, is giving talk about Jensen at Christie's, comments; photo (M)",
"print_page": "41",
"blog": [],
"source": "The New York Times",
"multimedia": [],
"headline": {
"main": "From Denmark, Moonlight's Glow",
"kicker": "Antiques"
},
"keywords": [{
"name": "persons",
"value": "JENSEN, GEORG"
}, {
"name": "persons",
"value": "VON ESSEN, MICHAEL"
}, {
"name": "organizations",
"value": "CHRISTIE'S"
}, {
"name": "subject",
"value": "JEWELS AND JEWELRY"
}, {
"name": "subject",
"value": "ANTIQUES"
}, {
"name": "subject",
"value": "AUCTIONS"
}, {
"name": "subject",
"value": "ART"
}, {
"name": "subject",
"value": "SILVER"
}],
"pub_date": "2005-01-14T00:00:00Z",
"document_type": "article",
"news_desk": "Leisure/Weekend Desk",
"section_name": "Arts",
"subsection_name": null,
"byline": {
"person": [{
"organization": "",
"role": "reported",
"rank": 1,
"firstname": "Wendy",
"lastname": "Moonan"
}],
"original": "By Wendy Moonan"
},
"type_of_material": "News",
"_id": "4fd2a5708eb7c8105d88d3af",
"word_count": 1152,
"slideshow_credits": null
}]
},
"status": "OK",
"copyright": "Copyright (c) 2013 The New York Times Company. All Rights Reserved."
}
The Json Weburl data in the JSON can be accessed using the line: $y['response']['docs'][0]['web_url']
The 0 can be replaced with an index variable such as i to retrieve multiple web_url entries, and placed in a for loop.
for(i=0;i<3;i++)
{
$y['response']['docs'][i]['web_url']
}

Get the values in PHP of three objects in Tripadvisor JSON API file

Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.

Getting soundcloud images

I have been following this code: http://runnable.com/UuiMCfATvMMkAAAS/get-a-tracks-artwork-on-soundcloud-in-javascript
So to my understanding the url goes soundcloud.com/ARTISTID/TRACKID and I need to add those 2 details to the code: var PATH = "/users/ARTISTID/tracks/TRACKID ";
or is there an easier way?
Anyway what if a URL is "https://soundcloud.com/krewella/sets/enjoy-the-ride-the-remixes"
with "sets" included instead of track name?
Thanks
you can find information about how the URL's are formatted at soundcloud's API reference site
http://developers.soundcloud.com/docs/api/reference
there are a few ways you can modify the PATH variable.
A "set" is actually called a "playlist" in soundcloud API. From the docs: "A SoundCloud Set is internally called playlists due to some naming restrictions." For a "set" API entry point you will use a path like this:
PATH="/playlists/PLAYLISTID"
where PLAYLISTID of the link you provided is 25422993. This will return all the information you need about that playlist (artwork, tracks, ...). Here is the JSON returned from that PATH query:
{
"kind": "playlist",
"id": 25422993,
"created_at": "2014/03/03 20:06:31 +0000",
"user_id": 4562420,
"duration": 658451,
"sharing": "public",
"tag_list": "Enjoy the ride remixes armin van buuren vicetone electro house trance krewella",
"permalink": "enjoy-the-ride-the-remixes",
"track_count": 2,
"streamable": true,
"downloadable": false,
"embeddable_by": "all",
"purchase_url": "http://www.beatport.com/release/enjoy-the-ride/1255654",
"label_id": null,
"type": "",
"playlist_type": "",
"ean": "",
"description": "",
"genre": "",
"release": "",
"purchase_title": "BUY NOW ON BEATPORT",
"label_name": "",
"title": "Enjoy The Ride (The Remixes)",
"release_year": null,
"release_month": null,
"release_day": null,
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/playlists/25422993",
"permalink_url": "http://soundcloud.com/krewella/sets/enjoy-the-ride-the-remixes",
"artwork_url": "https://i1.sndcdn.com/artworks-000072616236-tz5ol2-large.jpg?435a760",
"user": {
"id": 4562420,
"kind": "user",
"permalink": "krewella",
"username": "Krewella",
"uri": "https://api.soundcloud.com/users/4562420",
"permalink_url": "http://soundcloud.com/krewella",
"avatar_url": "https://i1.sndcdn.com/avatars-000013271556-x3q1d7-large.jpg?435a760"
},
"tracks": [
{
"kind": "track",
"id": 137740360,
"created_at": "2014/03/03 19:41:39 +0000",
"user_id": 4562420,
"duration": 367446,
"commentable": true,
"state": "finished",
"original_content_size": 64800466,
"sharing": "public",
"tag_list": ""enjoy the ride" "armin van buuren" remix trance",
"permalink": "enjoy-the-ride-armin-van-buuren-remix",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": "http://www.beatport.com/release/enjoy-the-ride/1255654",
"label_id": null,
"purchase_title": "BUY ON BEATPORT",
"genre": "krewella",
"title": "Enjoy The Ride (Armin Van Buuren Remix)",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "wav",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/137740360",
"user": {
"id": 4562420,
"kind": "user",
"permalink": "krewella",
"username": "Krewella",
"uri": "https://api.soundcloud.com/users/4562420",
"permalink_url": "http://soundcloud.com/krewella",
"avatar_url": "https://i1.sndcdn.com/avatars-000013271556-x3q1d7-large.jpg?435a760"
},
"permalink_url": "http://soundcloud.com/krewella/enjoy-the-ride-armin-van-buuren-remix",
"artwork_url": "https://i1.sndcdn.com/artworks-000072484399-f2sdhs-large.jpg?435a760",
"waveform_url": "https://w1.sndcdn.com/EIFcGdIgM3QG_m.png",
"stream_url": "https://api.soundcloud.com/tracks/137740360/stream",
"playback_count": 208363,
"download_count": 0,
"favoritings_count": 9058,
"comment_count": 467,
"attachments_uri": "https://api.soundcloud.com/tracks/137740360/attachments"
},
{
"kind": "track",
"id": 137740647,
"created_at": "2014/03/03 19:43:12 +0000",
"user_id": 4562420,
"duration": 291005,
"commentable": true,
"state": "finished",
"original_content_size": 11638342,
"sharing": "public",
"tag_list": ""enjoy the ride" Electro house remix vicetone",
"permalink": "enjoy-the-ride-vicetone-remix",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": "http://www.beatport.com/release/enjoy-the-ride/1255654",
"label_id": null,
"purchase_title": "BUY NOW ON BEATPORT",
"genre": "krewella",
"title": "Enjoy The Ride (Vicetone Remix)",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/137740647",
"user": {
"id": 4562420,
"kind": "user",
"permalink": "krewella",
"username": "Krewella",
"uri": "https://api.soundcloud.com/users/4562420",
"permalink_url": "http://soundcloud.com/krewella",
"avatar_url": "https://i1.sndcdn.com/avatars-000013271556-x3q1d7-large.jpg?435a760"
},
"permalink_url": "http://soundcloud.com/krewella/enjoy-the-ride-vicetone-remix",
"artwork_url": "https://i1.sndcdn.com/artworks-000072484512-3laoie-large.jpg?435a760",
"waveform_url": "https://w1.sndcdn.com/IEJtUQs75W9u_m.png",
"stream_url": "https://api.soundcloud.com/tracks/137740647/stream",
"playback_count": 216405,
"download_count": 0,
"favoritings_count": 9925,
"comment_count": 455,
"attachments_uri": "https://api.soundcloud.com/tracks/137740647/attachments"
}
],
"created_with": {
"id": 46941,
"kind": "app",
"name": "SoundCloud.com",
"uri": "https://api.soundcloud.com/apps/46941",
"permalink_url": "http://soundcloud.com/apps/v2-on-https-soundcloud-com",
"external_url": "",
"creator": "spadgos"
}
}
If you know the numerical track id (which you can get via the API call we made above) you can use that to play that specifc track.
PATH="/tracks/TRACKID"
If you want to get tracks of a user
PATH="users/USERID/tracks"
hope that helps!

Categories