How do I retrieve data from an external url using php? - 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?

Related

Change charts title by PhpOffice\PhpSpreadsheet in template

I try to change chart title in .xlsx template
I open template, change cels ,write to output.
Q: How to change chart title....
$reader = IOFactory::createReader( 'Xlsx' );
$reader->setIncludeCharts( true );
$spreadsheet = $reader->load( storage_path( 'app/template.xlsx' ) );
$spreadsheet->getActiveSheet()->setCellValue( 'B3', 'Blabla' );
//create new from template
$writer = new Xlsx( $spreadsheet );
$writer->setPreCalculateFormulas( true );
$writer->setIncludeCharts( true );
##how to change title in all/first charts in template?
I finally found the method. There are a few things to understand.
chartIndex - In an excel file, an id assigned to the chart based on the total number of charts starting from the first left most chart on a sheetA incrementing to the last right most chart on SheetC. This index is the entire collection of all charts on all sheets starting with chart1 and ending with chartX. If you have ten charts chart1,chart2,...chart10 and delete chart5, you will then have a new index of chart1,chart2....chart9, where the orig chart6-10 are all redindexed as chart5-9. In phpspreadsheet, this index appears to be represented with $chart->getName() ;, There is no corresponding setName() that would allow you to change/alter the index.
chartName - In an excel file, if you highlight a chart, in the upper left corner of the cells, above the A column, is a "chart name" drop down. You can name your charts for organization purposes. In excel, this field can be edited. In phpspreadsheet, I have yet to have find what object can get/set this field.
chartTitle - the in chart name of a chart, IE: "Annual Revenue Projections". In phpspreadsheet, this field is represented with $chart->getTitle->get/setCaptionText
So in order to find the chart you are looking to modify, you either must already know the chart index (ie: getName()) OR the chart visual title (ie: getCaptionText() ).
Because of adding deleting moving charts, I found it easier, in the excel template, to add visual titles to your charts then search for those titles/captionText in your code. This way you don't have to have worry about tracking which chart is which index. Use the getCaptionText to then get the getName() index.
foreach ($spreadsheet->getSheetByName("SheetName")->getChartCollection() as $chart) {
// if you know TITLE of the chart
// TITLE is the visible title in the chart
// Easy to know if you set the titles yourself in the template chart
// A template chart TITLE cannot be a cell reference, will cause an error on file import
if ($chart->getTitle()->getCaptionText() == "Chart_12") {
$curIndex = $chart->getName() ; // = "chart3"
$curTitle = $chart->getTitle()->getCaptionText() ; // "Chart_12"
$chart->getTitle()->setCaption("Quarterly Revenue Chart") ;
break ;
}
// if you know the NAME (chart id) the chart
// NAME is like the hidden chart index
if ($chart->getName() == "chart12") {
$chart->getTitle()->setCaption("New Chart Title") ;
break ;
}
}

Laravel 5.5 Console TV Bar Chart High Charts multipleDatasets and label

I have a Laravel 5.5 app that used this ConsoleTV Chart Package I used a barchart to visualize my data in a monthly report basis. I have the following query below.
$dt = Carbon::now()->year;
$anRequest = AnalysisRequest::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))->orderBy('service_id')
->get();
and in my chart
$barChart = Charts::database($anRequest, 'bar', 'highcharts')
->title("Monthly service request")
->elementLabel("Total requests")
->dimensions(1000, 500)
->responsive(false)
->groupByMonth(date('Y'), true);
This code is working perfectly fine and display all the data in by month but how can I add another dataSets or multipleDataSets instead of just having one sets of data to visualize.
For example I will have another query from the AnalysisRequest but with a specific resources.
Sample code below using multi
The query
$tags_jan = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '1')->count();
$tags_feb = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '2')->count();
$tags_mar = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '3')->count();
// and the list goes on which is bad
The charts using multi
$chart = Charts::multi('bar', 'highcharts')
// Setup the chart settings
->title("Total Reports for this year")
// A dimension of 0 means it will take 100% of the space
->dimensions(0, 400) // Width x Height
// This defines a preset of colors already done:)
// ->template("material")
// ->responsive(true)
// You could always set them manually
// ->colors(['#2196F3', '#F44336', '#FFC107'])
// Setup the diferent datasets (this is a multi chart)
->colors(['green', 'aqua', 'red', 'yellow'])
->dataset('Ads', [$ads_jan,$ads_feb,$ads_mar,$ads_apr,$ads_may,$ads_june,$ads_july,$ads_aug,$ads_sept,$ads_oct,$ads_nov,$ads_dec])
->dataset('Channels', [$channels_jan,$channels_feb,$channels_mar,$channels_apr,$channels_may,$channels_june,$channels_july,$channels_aug,$channels_sept,$channels_oct,$channels_nov,$channels_dec])
->dataset('Shows', [$shows_jan,$shows_feb,$shows_mar,$shows_apr,$shows_may,$shows_june,$shows_july,$shows_aug,$shows_sept,$shows_oct,$shows_nov,$shows_dec])
->dataset('Tags', [$tags_jan,$tags_feb,$tags_mar,$tags_apr,$tags_may,$tags_june,$tags_july,$tags_aug,$tags_sept,$tags_oct,$tags_nov,$tags_dec])
This code above also works fine but as you can see in the variable I am querying for each month for this year which is isn't quite good. How can I simplified this query or another way to solve this using multiple dataSets?
Appreciate if someone could help.
Thanks in advance.
The following code can be added after you have queried your database and you would like to post different graphs to the same view, I was using the code to plot a barchart and line chart on the same graph as specified below........ look at the dataset position 2 its line and bar
$chart = new unclaimed;
$chart->labels( $days );
$chart->dataset('Daily Visitors Bar', 'bar', $totalNumber )->color('white')->backgroundColor(['#009900','#8a8a5c','#f1c40f','#e67e22','#16a085','#2980b9']);
$chart->dataset('Daily Visitors Line', 'line', $totalNumber )->color('black') ->fill(false)->backgroundColor(['##8a8a5c','009900','#f1c40f','#e67e22','#16a085','#2980b9']);

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!

JSON KEY/VALUE to PHP variable

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? ;-)

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.

Categories