read xml on url by curl in magento 2 - php

as title, i want to read to parse xml on url by using curl in magento 2. but it not worked.
here is my code.
$om = \Magento\Framework\App\ObjectManager::getInstance();
$curl = $om->get('Magento\Framework\HTTP\Adapter\Curl');
$curl->setConfig([
'timeout' => 5
];
$curl->write(\Zend_Http_Client::GET,$link);
$data = $curl->read();
if ($data === false) {
return false;
}
$data = preg_split('/^\r?$/m', $data, 2);
$data = trim($data[1]);
$curl->close();

Related

PHP - Combine multiple API endpoints in array

I am trying to create a small function to load data from different API endpoints into one array to work with / load data from. Right now my code is looking as follow;
$url1 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/uhmotNBAQ6-0vi9PFysRBg/members';
$url2 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/DWkD4B0uSsGQoryrz8Nuwg/members';
$url3 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/wSbCgimqTPy470n-wDQXPQ/members';
$url4 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/nmc0HQW-TZirTlnGzwbF-w/members';
$url5 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/WpV4yaVxSLW8QXH2Be40cA/members';
$api_endpoint1 = json_decode(file_get_contents($url1), true);
$api_endpoint2 = json_decode(file_get_contents($url2), true);
$api_endpoint3 = json_decode(file_get_contents($url3), true);
$api_endpoint4 = json_decode(file_get_contents($url4), true);
$api_endpoint5 = json_decode(file_get_contents($url5), true);
$merged_data = array();
foreach ($api_endpoint1 as $data) {
foreach ($api_endpoint2 as $data2) {
$merged_data[] = array_merge($data, $data2[$data['Name']]);
}
}
var_dump($merged_data);
It doesn't work as I tried so many things the past two days, I came to search for help.
Huge thanks to #barrycarter for his help in pushing me into the right direction.
The actual code needed to be like this:
$url1 = 'gameinfo.albiononline.com/api/…';
$url2 = 'gameinfo.albiononline.com/api/…';
$url3 = 'gameinfo.albiononline.com/api/…';
$url4 = 'gameinfo.albiononline.com/api/…';
$url5 = 'gameinfo.albiononline.com/api/…';
$merged_urls = [$url1, $url2, $url3, $url4, $url5];
$api_endpoint = [];
foreach ($merged_urls as $urls) {
$api_endpoint[] = file_get_contents($urls);
}
// Gives all DATA from all Guilds members
// var_dump($api_endpoint);
$merged_arrays = array_merge(json_decode($api_endpoint[0], true), json_decode($api_endpoint[1], true), json_decode($api_endpoint[2], true), json_decode($api_endpoint[3], true), json_decode($api_endpoint[4], true));
foreach ($merged_arrays as $query) {
echo $query['Name'];
echo '<br>';
}

Show only a specific part of html response in php

I am trying to get tracking information from amazon using provided url
https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302
I am getting response using file_get_contents() function in php,
what I want is to show only that part of the response which contains the tracking information as an output of my php script and eliminate/hide all the unnecessary content from file_get_contents() response.
One way to do what you're looking for is use DomDocument to filter out the json data in the source ($file) and then use a recursive function to get the elements you need.
You can set the elements you need using an array, $filter. In this example we've taken a sample of some of the available data, i.e. :
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
The code
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$trackingData = []; // store for order tracking data
$html = new DOMDocument();
#$html->loadHTML($file);
foreach ($html->getElementsByTagName('script') as $a) {
$data = $a->textContent;
if (stripos($data, 'shortStatus') !== false) {
$trackingData = json_decode($data, true);
break;
}
}
// set the items we need
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
// invoke recursive function to pick up the data items specified in $filter
$result = getTrackingData($filter, $trackingData);
echo '<pre>';
print_r($result);
echo '</pre>';
function getTrackingData(array $filter, array $data, array &$result = []) {
foreach($data as $key => $value) {
if(is_array($value)) {
getTrackingData($filter, $value, $result);
} else {
foreach($filter as $item) {
if($item === $key) {
$result[$key] = $value;
}
}
}
}
return $result;
}
Output:
Array
(
[orderId] => 203-2171364-3066749
[shortStatus] => IN_TRANSIT
[promiseMessage] => Arriving tomorrow by 9 PM
[lastTransitionPercentComplete] => 92
[lastReachedMilestone] => SHIPPED
[shipmentId] => 23796758607302
)
Try this
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$html = new DOMDocument();
#$html->loadHTML($file);
foreach($html->getElementsByTagName('span') as $a) {
$property=$a->getAttribute('id');
if (strpos($property , "primaryStatus"))
print_r($property);
}
?>
It should show "Arriving tomorrow by 9 PM" status.

Only text on the website when i put the api

I have this API for redtube but when I put this in my .php file and show the site theres comes up this, why the site does not show the videos, its only text on the site when I preview the site. Nothing shows video.
Can someone help me or know what I am doing wrong ?
`
// Simple url builder function.
// You can use CURL for passing HTTP GET parameters and to call the RedTube API.
function RedTubeApiCall($http_server, $params = array())
{
$query_string = '?';
if(is_array($params) && count($params)){
foreach($params as $k=>$v){
$query_string .= $k.'='.$v.'&';
}
$query_string = rtrim($query_string,'&');
}
$content = file_get_contents($http_server.$query_string);
return $content;
}
$http = 'http://api.redtube.com/';
$call = 'redtube.Categories.getCategoriesList';
$params = array(
'output' => 'xml',
'data' => $call
);
$response = RedTubeApiCall($http , $params);
if ($response) {
// handle the response
}
// Simple url builder function.
// You can use CURL for passing HTTP GET parameters and to call RedTube API.
function RedTubeApiCall($http_server, $params = array())
{
$query_string = '?';
if(is_array($params) && count($params)){
foreach($params as $k=>$v){
$query_string .= $k.'='.$v.'&';
}
$query_string = rtrim($query_string,'&');
}
$content = file_get_contents($http_server.$query_string);
return $content;
}
$http = 'http://api.redtube.com/';
$call = 'redtube.Categories.getCategoriesList';
$params = array(
'output' => 'xml',
'data' => $call
);
$response = RedTubeApiCall($http , $params);
if ($response) {
// handle the response
}
?>``

How to re-build URL to make sure parameter sent

I'm making a function that can perform queries to maps.googleapis.com. I use the library GuzzleHttp assistance.
The problem I faced is when I create a function and try to access the functionality by adding parameters in URL. Looks like this function doesn't known parameters (unallocated) consequently the function that I made did not work properly.
My Controller
public function actionGetalldata() {
$url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=alskdsbeKASDJldkd&types=geocode&language=id&input=paci";
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $url);
$data = $res->getBody();
$array = json_decode($data, true);
foreach ($array['predictions'] as $key) {
$detail = $this->getLatLong($key['place_id']);
}
}
You see... When I try to loop my whole data, I call getLatLong function but always fail because the function can not accept the parameters that I provide.
Below is the function
function getLatLong($placeid) {
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=alskdsbeKASDJldkd";
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $url);
$data = $res->getBody();
$array = json_decode($data, true);
$resultx = $array['result'];
$id = $resultx['id'];
$placeid = $resultx['place_id'];
$alamat = $resultx['adr_address'];
$lat = $resultx['geometry']['location']['lat'];
$long = $resultx['geometry']['location']['lng'];
$allData = [
'id' => $id,
'place_id' => $placeid,
'address' => $alamat,
'lat' => $lat,
'long' => $long
];
return $allData;
}
It looks like the $placeid variable is the cause.
If I directly place a static placeid value, this function working.
How can I fix it? Please help
Thank you

Looking for something in json file then trying something else if it doesnt work

Im getting json files from a site and i want it to find which ever one gets the file and use that one. Im using the $_GET Method too. There are 2 ways of getting the same file but they both require an id or a custom url from steam.
My url example: www.mysite.com?id=123123123
2 ways of getting json file:
http://steamcommunity.com/id/ID/inventory/json/730/2
http://steamcommunity.com/CUSTOMURL/76561198051643107/inventory/json/730/2
How im decoding it:
$id = $_GET['id'];
$url = "http://steamcommunity.com/id/".$id."/inventory/json/730/2";
$content = file_get_contents($url);
$playerinfo = json_decode($content, true);
$InventoryStatus = $playerinfo['success'];
some ref
$id = $_GET['id'];
$handlers =array(
'getByJson','getByDB','getBySomething'
);
$result = array('handler'=>'','data'=>'');
then call $handlers
foreach($handlers as $m){
$methodResult = call_user_func($m,$id);
if($methodResult !==false){
$result = array('handler'=>$m, 'data' => $methodResult) ;
break;
}
}
handler something like this
function getByJson($id){
$url = "http://steamcommunity.com/id/".$id."/inventory/json/730/2";
$string = file_get_contents($url);
$isJson =is_string($string) && is_object(json_decode($string)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
if($isJson){
$playerinfo = json_decode($content, true);
return $playerinfo['success'];
}
return false;
}
function getByDB($id){
// get $result
if(condition){
return $result
}
return false;
}
function getBySomething($id){
// get $result
if(condition){
return $result
}
return false;
}

Categories