API related with XML? - php

Is it done correctly? I am still confused with how api works. I am newbie. I have gone around google to find answers. I followed tutorial and tried to modify it. It is basic one.
I would like to retrieve the images of products which is on sale (mode=hot) for slideshow. I will appreciate the help if you could help me to understand how api shld be done.
EDIT
I am trying to pull the images from database in pinnacle cart. so i wanted to list out what it have in xml. All xml you see below is on source view but not on webpage itself, is it normal? Also when I am trying to show the images on webpage and the images don't appear. I am not sure where I went wrong.
<Product>
<Price><![CDATA[695.00000]]></Price>
<Visible><![CDATA[Yes]]></Visible>
<Taxable><![CDATA[Yes]]></Taxable>
<Weight><![CDATA[0.00]]></Weight>
<UPC><![CDATA[]]></UPC>
<Sku><![CDATA[]]></Sku>
<Title><![CDATA[Necklace]]></Title>
<URL><![CDATA[https://xxxxx/staging/index.php?p=product&id=80]]></URL>
<ThumbnailImageUrl><![CDATA[http://www.xxxxxxxxxx.com/staging/images/products/thumbs/100040.jpg]]></ThumbnailImageUrl>
<ImageUrl><![CDATA[http://www.xxxxxxxx.com/staging/images/products/100040.jpg]]></ImageUrl>
<Discontinued><![CDATA[No]]></Discontinued>
<Options> </Options>
<Added><![CDATA[2010-05-12 13:50:00]]></Added>
<ManufaturerName><![CDATA[]]></ManufaturerName>
<Description><![CDATA[<p> </p><p> </p>]]></Description>
<AmazonId><![CDATA[]]></AmazonId>
<AmazonItemCondition><![CDATA[]]></AmazonItemCondition>
<AmazonIdType><![CDATA[]]></AmazonIdType>
<EbayCategoryId><![CDATA[]]></EbayCategoryId>
<YahooPath><![CDATA[]]></YahooPath>
<GoogleItemCondition><![CDATA[]]></GoogleItemCondition>
<PricegrabberCategory><![CDATA[]]></PricegrabberCategory>
<PricegrabberItemCondition><![CDATA[]]></PricegrabberItemCondition>
<PricegrabberPartNumber><![CDATA[]]></PricegrabberPartNumber>
<InventoryControl><![CDATA[Yes]]></InventoryControl>
<PID><![CDATA[80]]></PID>
<ProductId><![CDATA[100040]]></ProductId>
<Qoh><![CDATA[1]]></Qoh>
<NextagCategory><![CDATA[]]></NextagCategory>
<NextagPartNumber><![CDATA[]]></NextagPartNumber>
<NextagItemCondition><![CDATA[]]></NextagItemCondition>
</Product>
My code
<?php
$shop='www.xxx.com/staging/content/admin/plugins/openapi/index.php?';
$user = "asd";
$password = "ad";
$token = 'token';
// Assemble the account url
$url = 'https://'.$shop."username=".$user."&password=".$password."&token=".$token. "&apiType=xml&call=GetProducts&mode=hot";
// Setup the cURL object
$curl = curl_init();
curl_setopt($l_oCurl, CURLOPT_POST, 1);
curl_setopt( $curl, CURLOPT_URL, $url );
$response=curl_exec($curl);
curl_close($curl);
$image_xml = new SimpleXMLElement($response);
**foreach($xml->ThumbnailImageUrl as $thumbs){
echo "<img src=".$thumbs."/>";**
}
?>

SimpleXml can load remote URLs with simplexml_load_file and all libxml bases extensions can be used with a custom Stream Context. Just create your custom context with stream_context_create and then set it with libxml_set_streams_context. See Context List and Options
To generate a URL encoded string, use http_build_query
As for using SimpleXml, please see the Basic Usage Examples in the PHP Manual. You basically just have to traverse to the node and echo it, e.g.
echo $sxe->someNode->someOtherNode->ThumbnailImageUrl;

Related

How to get json data without api

I'm trying to get the viewer count so I can check if a streamer is online on https://www.dlive.tv/. If you view the page source on a streamer's page (https://www.dlive.tv/thelongestchain), there's a bunch of json and "watchingCount" is there.
Basically, I want to have the streamer appear on the "Live Now" section of my site if their viewer count is 1 or more, but I can't figure out anyway on how to get the viewer count. I know I could use something like Selenium if I was using python and could run it from my pc, but I need the site to know it.
DLive doesn't have an api yet, so I don't know how to make a call(or request I don't know the terminology) to get this info. When I look in the network tab on chrome I see that there's a call (https://graphigo.prd.dlive.tv/) that provides stream info I think. Would I also need my authkey?
I realize this question is broad and all over the place but it's because so am I with me trying to solve this the last couple days. If I had the viewercount as a variable, I know how to display the streamer on the "Live Now" section of my site, I just don't know how to get the necessary data.
If there's another way I should be checking if a streamer is online or offline other than getting the viewercount, that would work too. If anyone could help me out I would greatly appreciate it, thanks.
I tried scraping the page but I don't think you can scrape dynamic content. When I tried to use SimpleHTMLDom it just returned static elements.
<?php
require 'simple_html_dom.php';
$html = file_get_html('https://www.dlive.tv/thelongestchain')
if(($html->find('video', 0))) {
echo 'online';
}else{
echo 'offline';
}
/* The video element is only on the page if the streamer is live, but it doesn't return because it's not static I presume */
?>
I have no idea at all how to go about making a call/request to get the json data for the viewer count, or how to get any other data that could check if a streamer is online. All the scraping I've done did not return any elements that weren't static (the same no matter if the streamer was online or offline).
Try cURL, it's like a magic wand.
This will return the entire page, and I think including the JSON you're looking for:
<?php
$curl = curl_init('https://www.dlive.tv/thelongestchain');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
var_dump($result); // you do as you need to here
curl_close($curl);
?>
Here's the <script> containing the data I believe you need. Assuming "watchingCount" is the same thing you're looking for?
<script>window.__INITIAL_STATE__={"version":"1.2.0","snackbar":{"snackbar":null},"accessToken":{"accessToken":null},"userMeta":{"userMeta":{"fingerprint":null,"referrer":{"isFirstTime":true,"streamer":null,"happyHour":null,"user":null},"ipStats":null,"ip":"34.216.252.62","langCode":"en","trackingInfo":{"rank":"not available","prevPage":"not available","postStatus":"not available"},"darkMode":true,"NSFW":false,"prefetchID":"e278e744-f522-480e-a290-8eed0fe83b07","cashinEmail":""}},"me":{"me":null},"dialog":{"dialog":{"login":false,"subscribe":false,"cashIn":false,"chest":false,"chestWinners":false,"downloadApp":false}},"tabs":{"tabs":{"livestreamMobileActiveTab":"tab-chat"}},"globalInfo":{"globalInfo":{"languages":[],"communityUpdates":[],"recommendChannels":[]}},"ui":{"ui":{"viewPointWidth":1920,"mq":4,"isMobile":false}}};(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());</script> <script>window.__APOLLO_STATE__={"defaultClient":{"user:dlive-00431789":{"id":"user:dlive-00431789","avatar":"https:\u002F\u002Fimages.prd.dlivecdn.com\u002Favatar\u002F5c1330d8-5bc8-11e9-ab17-865634f95b6b","__typename":"User","displayname":"thelongestchain","partnerStatus":"NONE","username":"dlive-00431789","canSubscribe":false,"subSetting":null,"followers":{"type":"id","generated":true,"id":"$user:dlive-00431789.followers","typename":"UserConnection"},"livestream":{"type":"id","generated":false,"id":"livestream:dlive-00431789+i7rCywMWg","typename":"Livestream"},"hostingLivestream":null,"offlineImage":"https:\u002F\u002Fimages.prd.dlivecdn.com\u002Fofflineimage\u002Fvideo-placeholder.png","banStatus":"NO_BAN","deactivated":false,"about":"#lovejonah\n\nJonah's NEW FRIENDS:\nhttps:\u002F\u002Fdlive.tv\u002FFlamenco https:\u002F\u002Fi.gyazo.com\u002F88416fca5047381105da289faba60e7c.png\nhttps:\u002F\u002Fdlive.tv\u002FHamsterSamster https:\u002F\u002Fi.gyazo.com\u002F984b19f77a1de5e3028e42ccd71052a0.png\nhttps:\u002F\u002Fdlive.tv\u002Fjayis4justice \nhttps:\u002F\u002Fdlive.tv\u002FDenomic\nhttps:\u002F\u002Fdlive.tv\u002FCutie\nhttps:\u002F\u002Fdlive.tv\u002FTruly_A_No_Life\n\n\n\n\n\n\n\n\n\n\n\n\nOur Socials:\nhttps:\u002F\u002Fwww.twitch.tv\u002Fthelongestchain\nhttps:\u002F\u002Fdiscord.gg\u002Fsagd68Z\n\nLINO website: https:\u002F\u002Flino.network\nLINO Whitepaper: https:\u002F\u002Fdocsend.com\u002Fview\u002Fy9qtwb6\nLINO Tracker : https:\u002F\u002Ftracker.lino.network\u002F#\u002F\nLINO Discord : https:\u002F\u002Fdiscord.gg\u002FTUxp3ww\n\nThe Legend of Lemon's: https:\u002F\u002Fbubbl.us\u002FNTE1OTA4MS85ODY3ODQwL2M0Y2NjNjRlYmI0ZGNkNDllOTljNDMxODExNjFmZDRk-X?utm_source=shared-link&utm_medium=link&s=9867840\n\nPC:\nAMD FX 6core 3.0ghz ddr3\n12GB RAM HyperFury X Blue ddr3\nCooler Master Hyper 6heatpipe cpu cooler\nGigabyte MB\n2 x EVGA 1070 FTW\nKingston SSD 120gb\nKingston SSD 240GB\nREDDRAGON Keyboard\nREDDRAGON Mouse\nBlack Out Blue Yeti Microphone\nLogitech C922\n\nApps Used:\nBig Trades Tracker: https:\u002F\u002Ftucsky.github.io\u002FSignificantTrades\u002F#\nMultiple Charts: \nhttps:\u002F\u002Fcryptotrading.toys\u002Fcrypto-panel\u002F\nhttps:\u002F\u002Fcryptowatch.net\n\n\n\n","treasureChest":{"type":"id","generated":true,"id":"$user:dlive-00431789.treasureChest","typename":"TreasureChest"},"videos":{"type":"id","generated":true,"id":"$user:dlive-00431789.videos","typename":"VideoConnection"},"pastBroadcasts":{"type":"id","generated":true,"id":"$user:dlive-00431789.pastBroadcasts","typename":"PastBroadcastConnection"},"following":{"type":"id","generated":true,"id":"$user:dlive-00431789.following","typename":"UserConnection"}},"$user:dlive-00431789.followers":{"totalCount":1000,"__typename":"UserConnection"},"livestream:dlive-00431789+i7rCywMWg":{"id":"livestream:dlive-00431789+i7rCywMWg","totalReward":"3243600","watchingCount":5,"permlink":"dlive-00431789+i7rCywMWg","title":"bybit 0.1eth HIGH LEVERAGE","content":"","category":{"type":"id","generated":false,"id":"category:11455","typename":"Category"},"creator":{"type":"id","generated":false,"id":"user:dlive-00431789","typename":"User"},"__typename":"Livestream","language":{"type":"id","generated":false,"id":"language:1","typename":"Language"},"watchTime({\"add\":false})":true,"disableAlert":false},"category:11455":{"id":"category:11455","backendID":11455,"title":"Cryptocurrency","__typename":"Category","imgUrl":"https:\u002F\u002Fimages.prd.dlivecdn.com\u002Fcategory\u002FCBAOENLDK"},"language:1":{"id":"language:1","language":"English","__typename":"Language"},"$user:dlive-00431789.treasureChest":{"value":"2144482","state":"COLLECTING","ongoingGiveaway":null,"__typename":"TreasureChest","expireAt":"1560400949000","buffs":[],"startGiveawayValueThreshold":"500000"},"$user:dlive-00431789.videos":{"totalCount":0,"__typename":"VideoConnection"},"$user:dlive-00431789.pastBroadcasts":{"totalCount":13,"__typename":"PastBroadcastConnection"},"$user:dlive-00431789.following":{"totalCount":41,"__typename":"UserConnection"},"ROOT_QUERY":{"userByDisplayName({\"displayname\":\"thelongestchain\"})":{"type":"id","generated":false,"id":"user:dlive-00431789","typename":"User"}}}};(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());</script>
I assume you'll then just have to throw in a loop and make the url dynamic to get through whatever streamers you're monitoring with your site.

Any idea how to connect to this API?

I tried to find any widget to show Tinkoof's bank currency rate, because it changes every 60sec., but nothing.
Finally I found this API, but there is no any documentation for it.
I tried to find any articles about parsing, but I guess there's no use in that because of absence of any tag.
I need to show the currency rate on my website via this API. Any idea?
Big thanks!
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://www.tinkoff.ru/api/v1/currency_rates";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://www.tinkoff.ru/api/v1/currency_rates');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
It looks pretty straightforward to me. For someone with a decent knowledge of PHP will do this, provided the output is:
Now with the above information, I would:
Get the result to PHP using file_get_contents().
Parse the result as an array using json_decode($contents, $true).
Using the above result, I would get display the value using: $output["payload"]["rates"][0]["buy"] or something similar.
At this time of writing, the above will get me 58:

How to get Wikipedia page HTML with absolute URLs using the API?

I'm trying to retrieve articles through wikipedia API using this code
$url = 'http://en.wikipedia.org/w/api.php?action=parse&page=example&format=json&prop=text';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$c = curl_exec($ch);
$json = json_decode($c);
$content = $json->{'parse'}->{'text'}->{'*'};
I can view the content in my website and everything is fine but I have a problem with the links inside the article that I have retrieved. If you open the url you can see that all the links start with href=\"/
meaning that if someone clicks on any related link in the article it redirects him to www.mysite.com/wiki/.. (Error 404) instead of en.wikipedia.com/wiki/..
Is there any piece of code that I can add to the existing one to fix this issue?
This seems to be a shortcoming in the MediaWiki action=parse API. In fact, someone already filed a feature request asking for an option to make action=parse return full URLs.
As a workaround, you could either try to mangle the links yourself (like adil suggests), or use index.php?action=render like this:
http://en.wikipedia.org/w/index.php?action=render&title=Example
This will only give you the page HTML with no API wrapper, but if that's all you want anyway then it should be fine. (For example, this is the method used internally by InstantCommons to show remote file description pages.)
You should be able to fix the links like this:
$content = str_replace('<a href="/w', '<a href="//en.wikipedia.org/w', $content);
In case anyone else needs to replace all instances of the URL.
You'll need to use regex and the g flag
/<a href="\/w/g

php - how to parse XML returned by an api call from a website?

I am currently developing a website which requires an API call to a social plugin website to obtain a user token. With the user token, I can call the website's login window and have the user log in with his/her login credentials to allow my app to obtain the required data.
When 1) I make the API call to the website, 2) it returns the URL with a user token in XML as shown below:
1)
Login
2)
<?xml version="1.0" encoding="UTF-8"?>
-<auth_token> <url>http://xxxxx.net/api/start_auth?token=7x1x81xfxxxxx5bxxxx3dx45trsda</url> <token>7x1x81xfxxxxx5bxxxx3dx45trsda</token> </auth_token>
However, I am relatively new to PHP and not sure what will be the right approach to handle this XML returned, and to redirect the website to "http://xxxxx.net/api/start_auth?token=7x1x81xfxxxxx5bxxxx3dx45trsda". Once redirected, I can have user to log in and get the information I needed.
I have tried using curl method as shown below, but I am not familiar with parsing the result of curl_exe() and redirecting the site using the parsed value. I have not been able to get it working yet, but I think there should be more php native way to handle the returned XML and to use that serialized XML objects for redirecting the website.
<?php $ch = curl_init(); ?>
<?php curl_setopt($ch, CURLOPT_URL, "http://xxxxx.net/api/get_auth_url.xml?akey=$myAppKey"); ?>
<?php curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); ?>
<?php $store = curl_exec($ch); ?>
<?php curl_close($ch); ?>
Any feedback will be much appreciated.
WL
i'd give SimpleXMLElement a shot once you've got your XML String (for which I'd also use curl_exec(), by the way) ...
$authTokenXml = new SimpleXMLElement( $store );
$authUrl = $authTokenXml->url
and now you can use $authUrl in any way you like, e.g. sending a http redirect header:
header('Location: ' . $authUrl);
or with another CURL.
Hope that helps!
(btw. you don't need the <?php-Tags in every line. It starts a php block, actually)
Start with the SimpleXML documentation

Parse an XML webpage using PHP

How do I use PHP to parse XML on the web?
Here is the example XML. How would you get the value of the first "AskRealtime"?
I am aware of SimpleXML. I am looking for the proper code to open the XML webpage, and work with it using SimpleXML.
This suggested code does not succesfully load the page:
$xml = #simplexml_load_file("http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
$price = $xml->results->quote[0]->AskRealtime;
echo $price;
Have you tried using SimpleXMLElement? It works just like your code but it's constructed differently.
$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$xml = new SimpleXMLElement($url, null, true);
echo $xml->results->quote[0]->AskRealtime;
There are different methods for getting the file contents, even though I doubt it's the problem.
/* cURL */
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
curl_close($curl);
/* Alternative */
$contents = file_get_contents($url);
Can you tell what is the error you get? Or try var_dump($xml) and see what it returns.
Step 1. - load the file in SimpleXML $xml = #simplexml_load_file($fl) or die($errorMsg);where $fl is the file URL and $errorMsg is the error message to display.
Step 2. - get a content $whatever=$xml->results->quote->AskRealtime[0]; Explained: it goes to the XML, then what is named "results", then what is named "quote", then what is named AskRealtime, but the first (index 0) of it.
And a note: if, for some reason, you'll have to get something which is named whatever-else (so it has a - in the name), then it works only if you make the code $xml->{'whatever-else'}
Use can use some HTTP request library to get the file, e.g.: http://www.php.net/manual/en/function.http-get.php
Then feed the response to SimpleXML.

Categories