JSON KEY/VALUE to PHP variable - php
I'll get right to the point.
I'm trying to save data retrieved from an API using the following:
$i=0;
foreach($results->results as $product){
$products[$i]['pid'] = $product->listing_id;
$products[$i]['title'] = $product->title;
$products[$i]['url'] = $product->url;
$products[$i]['price'] = $product->price;
$products[$i]['quantity'] = $product->quantity;
$products[$i]['endtime'] = $product->ending_tsz;
$products[$i]['thumb'] = $product->results.Images[url_75x75];
Here is the JSON request:
{
"count":163,
"results":[
{
"listing_id":118973432,
"state":"active",
"user_id":27549667,
"category_id":68894752,
"title":"Funny I Love You Valentines Card - I Heart you Even More then a Nerd Loves Starwars - Adult Funny Humor Greeting Cards",
"description":"You know how much Nerds be loving the Star Wars , this Valentines day show the one you love that you love them even more then that - The perfect greeting card for that special someone!\r\n\r\nGUARANTEED CHRISTMAS DELIVERY - Place your orders by 12\/19 and get it by Christmas Eve - Upgraded Two Shipping available starting at $5, just contact us to upgrade\r\n\r\nDetails:\r\n\r\n- Outside Message: I love you even more then a nerd loves Starwars\r\n- Inside Message: Blank Inside\r\n- Size A7 (5x7)\r\n- Matching White Envelope included \r\n- Packaged in a cello sleeve for protection in transit\r\n\r\nWe will gladly ship to your recipient! Just specify a ship to address and any special message in "notes to seller" at checkout. Need a Custom Card, Magnet or keychain, we do that too!\r\n\r\nShipping:\r\nUS S&H is $2-Ships within 1 business day. Please allow 2-5 business days for delivery.\r\nIntl S&H is $4 - Ships within 1 business day - Please allow 7-10 business days for delivery.\r\n\r\nBuy MORE and SAVE on shipping! Express shipment is available to most US cities contact us for price and details.\r\n\r\nFor More Rude, crude and downright funny greeting cards, novelty gifts and prints, visit our Etsy store and browse a large selection single cards, greeting card sets, prints and more totally edgy, racy, adult, crass, lude, perverted and all things nasty!\r\nimjustsayininc.etsy.com",
"creation_tsz":1422565585,
"ending_tsz":1432929985,
"original_creation_tsz":1356746393,
"last_modified_tsz":1422565585,
"price":"4.00",
"currency_code":"USD",
"quantity":3,
"tags":[
"funny card",
"greeting card",
"novelty card",
"mature card",
"adult card",
"cards",
"funny cards",
"relationship card",
"love card",
"i love you card",
"valentines cards",
"funny valentine",
"valentines day card"
],
"category_path":[
"Paper Goods",
"Cards",
"Valentine"
],
"category_path_ids":[
69150367,
69152963,
68894752
],
"materials":[
"Papaer",
"Ink",
"Envelope"
],
"shop_section_id":12656719,
"featured_rank":null,
"state_tsz":1421921498,
"url":"https:\/\/www.etsy.com\/listing\/118973432\/funny-i-love-you-valentines-card-i-heart?utm_source=massetsy&utm_medium=api&utm_campaign=api",
"views":764,
"num_favorers":102,
"shipping_template_id":null,
"processing_min":1,
"processing_max":1,
"who_made":"i_did",
"is_supply":"false",
"when_made":"2010_2015",
"is_private":false,
"recipient":"unisex_adults",
"occasion":"valentines",
"style":null,
"non_taxable":false,
"is_customizable":true,
"is_digital":false,
"file_data":"",
"language":"en-US",
"has_variations":false,
"used_manufacturer":false,
"Images":[
{
"listing_image_id":410447372,
"hex_code":"C1AFB1",
"red":193,
"green":175,
"blue":177,
"hue":353,
"saturation":9,
"brightness":75,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":1,
"url_75x75":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_75x75.410447372_sjo4.jpg",
"url_170x135":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_170x135.410447372_sjo4.jpg",
"url_570xN":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_570xN.410447372_sjo4.jpg",
"url_fullxfull":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_fullxfull.410447372_sjo4.jpg",
"full_height":737,
"full_width":600
},
{
"listing_image_id":402927400,
"hex_code":"897761",
"red":137,
"green":119,
"blue":97,
"hue":33,
"saturation":29,
"brightness":53,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":2,
"url_75x75":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_75x75.402927400_e80x.jpg",
"url_170x135":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_170x135.402927400_e80x.jpg",
"url_570xN":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_570xN.402927400_e80x.jpg",
"url_fullxfull":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_fullxfull.402927400_e80x.jpg",
"full_height":800,
"full_width":986
},
{
"listing_image_id":402923983,
"hex_code":"C8C1C0",
"red":200,
"green":193,
"blue":192,
"hue":8,
"saturation":4,
"brightness":78,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":3,
"url_75x75":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_75x75.402923983_snri.jpg",
"url_170x135":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_170x135.402923983_snri.jpg",
"url_570xN":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_570xN.402923983_snri.jpg",
"url_fullxfull":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_fullxfull.402923983_snri.jpg",
"full_height":440,
"full_width":640
}
]
}
],
"params":{
"limit":"1",
"offset":0,
"page":null,
"shop_id":"imjustsayininc",
"keywords":null,
"sort_on":"created",
"sort_order":"down",
"min_price":null,
"max_price":null,
"color":null,
"color_accuracy":0,
"tags":null,
"category":null,
"translate_keywords":"false",
"include_private":0
},
"type":"Listing",
"pagination":{
"effective_limit":1,
"effective_offset":0,
"next_offset":1,
"effective_page":1,
"next_page":2
}
}
What I'm trying to do is pull all values from the image field where it shows an image URL (url_75x75,url_170x135,url_570xN & url_fullxfull).
I seem to be stuck only on the importing of the images. They seems to be in an array and I can't figure out how to implement pulling them like I do the rest of the content.
I've spent roughly 3 days searching, trying and failing at doing this.
I was successful when I had the Json request split up into separate requests but recently learned I could include images into one JSON request which is the method I am currently trying.
How can I do this?
I'm pretty new to PHP and I'm even newer at JSON so please be descriptive as possible and try not to overload me with complex ways I could do this, thank you.
results is an array of objects, so is Images
I didn't test it but I think something like this should be able to retrieve the first image of the first result:
$product->results[0]->Images[0]->url_75x75
In your code, this is obviously wrong:
$product->results.Images[url_75x75]
Javascript with PHP syntax mixed together? ;-)
Related
get CSGO inventory with steam API
OK, i need to get csgo inventory with steam API . i use this url https://api.steampowered.com/IEconItems_730/GetPlayerItems/v1key=$api_key&steamids=$steamid and i use this url for access to all csgo items. https://api.steampowered.com/IEconItems_730/GetSchema/v2 problem 1, is i cant understand the returned value in first url. there is no item name, image and ... . this is how it will return "id": 547938992, "original_id": 547938992, "defindex": 13, "level": 1, "quality": 4, "inventory": 53, "quantity": 1, "rarity": 1, "attributes": problem 2, when is use second url to get all of csgo skins. it just returns vanilla skins. how can i get full skins like other websites : opskins , bitskins, csgolounge and .... . I know there is alot of question like this in Stackoverflow but none of them answer the way i can understand. and I am sorry for my poor English.
For my project I use another url for steam's API, "http://steamcommunity.com/profiles/*insert steamId*/inventory/json/730/2" You can try to use your steamID and paste it into your browser and you will see how the response looks like. This is what you will be working with. If you make a request with this url you will get a response with a json object which have two parts. One part is called rgInventory(ie. data.rgInventory)and contains ids for each skin in the users csgo-inventory. The second part is called rgDescriptions(ie. data.rgDescriptions) and contains info/name/img url for each skin. To add the info to the skins the user have in rgInventory you need to compare the classId for each item on both the rgInventoryand rgDescriptions. The classIdis the id which decide which type of weapon it is, therefore the classid is not unique. So what Im doing is using two for-loops, and compares the ids so I can add the item_url, market_name etc. To the rgInventory array which I then I send away as the callback. Like this (javascript): var ids = getID(data.rgInventory); var item = getItems(data.rgDescriptions); for (var i = 0; i < ids.length; i++) { for (var k = 0; k < item.length; k++) { if (ids[i].classid == item[k].classid) { ids[i].market_name = item[k].market_name; ids[i].icon_url = item[k].icon_url; ids[i].tradable = item[k].tradable; } } } So if the classids of both items is the same I will add the information I want to the variable "ids" which in this case is a copy of rgInventory. When the for-loops are done I send away the ids-variable as my callback. Feel free to ask questions, and sorry if this is confusing. Remember to type the url I linked with your steam-profile in your browser and see the result. Hope it helps!
Displaying Output from Basic API (PHP)
So I am using an API (SendInBlue - a transactional email service) and I am trying to use the API to display a list of the users on my webpage. Below, SendInBlue has given me sample code to use, however when I put them together I just get a blank screen. I know this is a total beginner question... but how do I put these 2 pieces of code together so that it actually displays the list of contacts on my website? Thank you so much!! EXAMPLE require('../mailin.php'); $mailin = new Mailin("https://api.sendinblue.com/v2.0","your access key"); $data = array( "listids" => array(1,2), "timestamp" =>"2015-05-22 14:30:00", "page" => 1, "page_limit" => 2 ); var_dump($mailin->display_list_users($data)); SAMPLE OUTPUT { "code":"success", "message":"Retrieved details of all users for the given lists", "data":{ "data":[ { "blacklisted":0, "email":"email1#domain.com", "id":1, "listid":[1], "blacklisted_sms":1, "last_modified" : "2015-05-22 15:30:00" }, { "blacklisted":1, "email":"email2#domain.com", "id":2, "listid":[1,2], "blacklisted_sms":0 , "last_modified" : "2015-05-25 19:10:30" } ], "page":1, "page_limit":2, "total_list_records":100 } }
Ok I figured this out. I turned every attribute into a variable like so... $subscriberemail = $getemails['data']['data'][$number]['email']; This took ages to figure out!
How to implement pushState() and popState() with ajaxed content in JSON format?
Short Version What content does the content.php file referenced in this tutorial have? http://moz.com/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate Long Version With Research The tutorial above is the most succinct I have come across for implementing pushState() and popState() in a scenario where you are loading content via Ajax but want to retain bookmarking and browser backwards and forwards navigation functionality: A demo page has been set up as a proof of concept: http://html5.gingerhost.com/ Where the source code is as below. There are several in-between steps needed to implement it however that I'm not totally familiar with: Setting up a PHP file of content in JSON format Understanding JSON formatting A comment on this post html5 pushstate example and jquery's $.getJSON suggests using Firebug to see the HTTP request response in order to see the JSON formatting. With Firebug loaded, and Console > All selected, when I click on the navigation links I see entries like: GET http://html5.gingerhost.com/content.php?cid=%2F&format=json 200 OK 869ms GET http://html5.gingerhost.com/content.php?cid=%2Fseattle&format=json 200 OK 859ms GET http://html5.gingerhost.com/content.php?cid=%2Fnew-york&format=json 200 OK 837ms GET http://html5.gingerhost.com/content.php?cid=%2Flondon&format=json 200 OK 863ms The corresponding content from the 'Reponse' tab for each entry is in the JSON format: {"title":"Title value here","h1":"H1 value here","article #articletext":"<p>Lots of html here.<\/p><p>That includes escaped characters.<\/p>","#image":"<img class=\"thumbnail\" alt=\"\" src=\"and_an_image.jpg\">"} So after some research, JSON format seems to be: { "myArrayName": [ { "Key1":"Value1" , "Key2":"Value2" }, // object one { "Key1":"Value3" , "Key2":"Value4" }, // object two { "Key1":"Value5" , "Key2":"Value6" }, // object three ] } Adding a 'real world' example to that would make it: { "myCDCollection": [ { "Title":"Trash" , "Artist":"Alice Cooper" }, // object one { "Title":"Dr. Feelgood" , "Artist":"Motley Crue" }, // object two { "Title":"Cherry Pie" , "Artist":"Warrant" }, // object three ] } So the keys in the proof of concept seem to be: title h1 article #articletext #image So my question is what content does the content.php file referenced in the tutorial need to have? Is it just a matter of copying and pasting the JSON objects, separated by commas? Do they need to be encapsulated in an array? Does the array need a name? Which is then encapsulated in curly braces? Does the PHP file need a MIME media type specified, if so where and how? Here is the script from the proof of concept: <script> // THIS IS WHERE THE MAGIC HAPPENS $(function() { $('nav a').click(function(e) { $("#loading").show(); href = $(this).attr("href"); loadContent(href); // HISTORY.PUSHSTATE history.pushState('', 'New URL: '+href, href); e.preventDefault(); }); // THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL window.onpopstate = function(event) { $("#loading").show(); console.log("pathname: "+location.pathname); loadContent(location.pathname); }; }); function loadContent(url){ // USES JQUERY TO LOAD THE CONTENT $.getJSON("content.php", {cid: url, format: 'json'}, function(json) { // THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES $.each(json, function(key, value){ $(key).html(value); }); $("#loading").hide(); }); // THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL $('li').removeClass('current'); $('a[href="'+url+'"]').parent().addClass('current'); } </script>
It doesn't matter what content.php contains, it is just supposed to return some content that is then manipulated by javascript and loaded into the DOM. You can't really determine what his content.php contains, but given the limited scope of the page, here is one possibility: <?php $page = $_GET['cid']; $pageData = array(); switch ($page) { case '/': $pageData = array( 'title' => 'Seattle - Part of a demo for #ProSEO', 'h1' => 'Seattle', 'article #articletext' => '<p>Seattle is the northernmost major city in the contiguous United States, and the largest city in the Pacific Northwest and the state of Washington. It is a major seaport situated on a narrow isthmus between Puget Sound (an arm of the Pacific Ocean) and Lake Washington, about 114 miles (183 km) south of the Canada - United States border, and it is named after Chief Sealth \"Seattle\", of the Duwamish and Suquamish native tribes. Seattle is the center of the Seattle-Tacoma-Bellevue metropolitan statistical area--the 15th largest metropolitan area in the United States, and the largest in the northwestern United States.<\/p><p>Seattle is the county seat of King County and is the major economic, cultural and educational center in the region. The 2010 census found that Seattle is home to 608,660 residents within a metropolitan area of some 3.4 million inhabitants. The Port of Seattle, which also operates Seattle-Tacoma International Airport, is a major gateway for trade with Asia and cruises to Alaska, and is the 8th largest port in the United States in terms of container capacity.<\/p>', '#image' => '<img class=\"thumbnail\" alt=\"\" src=\"seattle.jpg\">' ); break; case '/new-york': $pageData = array( 'title' => 'New York - Part of a demo for #ProSEO', 'h1' => 'New York', 'article #articletext' => '<p>New York is the most populous city in the United States and the center of the New York metropolitan area, which is one of the most populous metropolitan areas in the world. New York City exerts a significant impact upon global commerce, finance, media, culture, art, fashion, research, technology, education, and entertainment. As the home of the United Nations Headquarters, it is also an important center for international affairs. The city is often referred to as New York City or the City of New York, to distinguish it from the state of New York, of which it is a part.<\/p>', '#image' => '<img class=\"thumbnail\" alt=\"\" src=\"new-york.jpg\">' ); break; case '/london': // similar code for london break; case '/seattle': // similar code for seattle break; } header('Content-Type: application/json'); echo json_encode($pageData); ?> In reality it most likely retrieves the page data from an external source like a database. Is it just a matter of copying and pasting the JSON objects, separated by commas? Do they need to be encapsulated in an array? Nothing needs to be encapsulated in an array - it doesn't matter how it gets there (you could generate the JSON yourself manuallly) as long as that's what the output is (a json-valid file). And you specify the MIMEtype of the response to application/json using the header method in PHP.
How do I retrieve data from an external url using php?
This is the current code that I have in order to retrieve the sizes for a particular product, however when an item has multiple drop-downs such as this one does for color. You must first select the color before retrieving the sizes for that color. I will need to retrieve both sets of data; colors and sizes. It seems if I am not mistaken that this site uses the JSON structure. I am a VERY novice learner and would like guidance on what to do next in order to retrieve the data using php... Thanks in advance! :) <?php $doc = new DOMDocument(); #$doc ->loadHTMLFile('http://www.drjays.com/shop/P1543932/'); $xpath = new DOMXPath($doc); $size = $xpath->query('//*[contains(#class, \'product_dropdown\')]'); foreach ($size as $sizes) { echo $sizes->nodeValue .PHP_EOL; } ?> update: I was able to use Google Chrome (developer tools) to retrieve this information. I believe this is confirmation that it is in fact JSON. "description" : "The Lace Inset Tie Front Woven Top by Apple Bottoms features:\r\n<br>\r\n<ul>\r\n<li> US sizing</li>\r\n<li> Pieced lace accents on shoulders</li>\r\n<li> Metal stud trim</li>\r\n<li> Two chest pockets</li>\r\n<li> Button-down closure</li>\r\n<li> Sleeveless cut</li>\r\n<li> Waist tie on front</li>\r\n\r\n<br>\r\n<b> Model is wearing size 1X</b>\r\n</ul>", "sizes" : [ { "id" : "1533783", "display" : "1X" }, { "id" : " 1533785", "display" : "2X" } ]
i don't think that is the url for the actual JSON object, with the google chrome developer tools can you find the object url?
XML to PHP array, and HTML Tags
Hi there i have got my feed functioning problem I have is in the xml there is description tag and inside is html code. now php is treating the HTML tags as other xml tags and making more arrays. How can I stop this from creating arrays out of the HTML tags? eg. <description> <h3>Some text</h3> </description> its out putting array['description'] => array['h3'] => "someText" PHP code: public function merchant_import_wahanda(){ if (!$this->session->userdata('logged_in')){ redirect('admin/login'); } $data['pageTitle'] = 'Merchant Admin'; $data['error_warning'] = ''; $data['success'] = ''; $xmlfile= 'http://www.wahanda.com/rss/mobdeal.xml'; $xmlRaw = file_get_contents($xmlfile); $this->load->library('xml'); $xmlData = $this->xml->xml_parse($xmlRaw); $this->load->model('admin/Deals_model', 'Deals'); $this->load->model('admin/Cities_model', 'Cities'); $this->load->model('admin/Partners_model', 'Partners'); //Get City ID foreach($xmlData["channel"]["item"] as $product){ $cityName[] = $product['w:location']["#content"]; } $cities = array_unique($cityName); foreach ($cities as $city){ if(!$this->Cities->getCityByName($city)){ $this->Cities->addFeedCity($city); } } //Get Partner ID foreach($xmlData["channel"]["item"] as $product){ $partnerName[] = $product['w:venues']['w:venue']['w:name']; } $partners = array_unique($partnerName); foreach ($partners as $partner){ if(!$this->Partners->getPartnerByName($partner)){ $this->Partners->addFeedPartner($partner); } } foreach($xmlData["channel"]["item"] as $product){ $cityID = $this->Cities->getCityByName($product['w:location']["#content"]); $partnerID = $this->Partners->getPartnerByName($product['w:venues']['w:venue']['w:name']); $deals[] = array( 'dealTitle' => $product['title'], 'price' => $product['w:price'], 'image' => $product['w:hiResImageLink'], 'buyLink' => $product['link'], 'startDate' => $product['w:startDate'], 'endDate' => $product['w:endDate'], 'partner' => $partnerID['partner_id'], 'city' => $cityID['city_id'], 'description' => $product['description'], 'RRP' => $product['w:rrp'], 'discount' => $this->getDiscount($product['w:price'], $product['w:rrp']) ); } ?><pre><?php var_dump($deals); ?></pre><?php foreach($deals as $deal){ $this->Deals->importWahanda($deal); } } XML Description example: <description> <a id="Wahanda_loves" name="Wahanda_loves"></a><h3>Wahanda loves</h3> <p>If you're fed up of shaving and can't bear the pain of waxing then remove hair the easy way with this course of IPL hair removal. It works by using beams of light to damage the hair follicle, meaning after a course of treatment you'll be hair-free for longer. Five sessions will catch the hair in each stage of the growth cycle so your skin will stay silky-smooth and fuzz-free for longer.</p> <a id="What.27s_in_it_for_you.3F" name="What.27s_in_it_for_you.3F"></a><h3>What's in it for you?</h3> <ul> <li>Five IPL Sessions on <b>one</b> of the following areas: <ul> <li>Lip and Chin</li> <li>Bikini Line</li> <li>Underarm</li></ul></li></ul> <ul> <li>Location: DepiCool, Leeds</li> <li>Available Monday - Saturday</li> <li><b>Strict voucher limit of 1 per person.</b> May buy multiples as gifts</li> <li>You will receive an eVoucher valid for one person to print out and take with you.</li> <li>Voucher valid for 6 months</li> <li>Cannot be used in conjunction with any other offer. Subject to availability. No cash alternative</li></ul> <p>You'll get a snazzy pair of goggles to wear during the treatment so your eyes are protected throughout the fifteen minute procedure. DepiCool's therapists are fully qualified and consider your comfort and safety to be the most important part of the treatment process. All staff are trained to be able to answer your questions so you'll be informed at at ease at all times. </p> <a id="Want_to_buy_this_as_a_gift.3F" name="Want_to_buy_this_as_a_gift.3F"></a><h3>Want to buy this as a gift?</h3> <p>If you're feeling generous and want to buy this as a gift for someone, don't worry - the voucher won't show the price or discount of the MobDeal if you add a gift message, making it perfect for giving as a gift. All you need to do is choose how many vouchers you'd like to buy at checkout so you can enter each recipient's name on the coupon, then add your message for the lucky recipient.</p></description>
You can either place your HTML into CDATA, as suggested by Agop, or encode the characters - use < instead of <, > instead of >, etc. As far as XML is concerned, they are identical. I'd go for the CDATA option since you have many lines of HTML, and it's more readable. <description> <![CDATA[<a id="Wahanda_loves" name="Wahanda_loves"></a><h3>Wahanda loves</h3> <p>If you're fed up of shaving and can't bear the pain of waxing then remove hair the easy way with this course of IPL hair removal. It works by using beams of light to damage the hair follicle, meaning after a course of treatment you'll be hair-free for longer. Five sessions will catch the hair in each stage of the growth cycle so your skin will stay silky-smooth and fuzz-free for longer.</p> <a id="What.27s_in_it_for_you.3F" name="What.27s_in_it_for_you.3F"></a><h3>What's in it for you?</h3> ... ]]> </description>
CDATA ?