I am experimenting with the Endicia shipping label server. The sample code below allows me to get a USPS label from their test server. How would I display the image that is being returned. Right now the print_r function (if un-commented out) does print out the array contents of what appears to be an image.
<?php
$strGetLabelURL = "https://www.envmgr.com/LabelService/EwsLabelService.asmx/GetPostageLabelXML";
$request = '<LabelRequest ImageFormat="GIF" Test="YES">
<RequesterID>abcd</RequesterID>
<AccountID>123456</AccountID>
<PassPhrase>samplePassPhrase</PassPhrase>
<MailClass>FIRST</MailClass>
<DateAdvance>0</DateAdvance>
<WeightOz>1</WeightOz>
<Stealth>FALSE</Stealth>
<Services InsuredMail="OFF" SignatureConfirmation="OFF" />
<Value>0</Value>
<Description>Sample Label</Description>
<PartnerCustomerID>12345ABCD</PartnerCustomerID>
<PartnerTransactionID>6789EFGH</PartnerTransactionID>
<ToName>Ben Franklin</ToName>
<ToCompany>United States Postal Service</ToCompany>
<ToAddress1>12345 Main Street</ToAddress1>
<ToCity>Camas</ToCity>
<ToState>WA</ToState>
<ToPostalCode>98607</ToPostalCode>
<ToPhone>2025551212</ToPhone>
<FromName>Technical Support</FromName>
<FromCompany>DYMO Endicia</FromCompany>
<ReturnAddress1>385 Sherman Ave.</ReturnAddress1>
<FromCity>Palo Alto</FromCity>
<FromState>CA</FromState>
<FromPostalCode>94306</FromPostalCode>
<FromZIP4>1864</FromZIP4>
<FromPhone>8005763279</FromPhone>
</LabelRequest>';
$params = array('http' => array(
'method' => 'POST',
'content' => 'labelRequestXML='.$request,
'header' => 'Content-Type: application/x-www-form-urlencoded'));
$ctx = stream_context_create($params);
$fp = fopen($strGetLabelURL, 'rb', false, $ctx);
if (!$fp)
{
print "Problem with $strGetLabelURL";
}
$response = stream_get_contents($fp);
if ($response === false)
{
print "Problem reading data from $url, $php_errormsg";
}
print_r($response);
?>
You have to load the XML, extract the image data, then put it in an image:
$sxml = Simplexml_load_string( $response );
echo '<img src="data:image/gif;base64,' . $sxml->Base64LabelImage . '">';
I don't know about Endicia solution but I think it's quite similar to UPS.
From the XML you send one can see that you ask for the label in GIF format.
I suppose that in the response you have an element named <LabelImage> or something similar. You need to extract the value that is between the opening and the closing tag and use below to print it on your browser:
echo '<img src="data:image/gif;base64,' . $value . '" alt="" />';
Related
I want to grab this number (28/28) with PHP from a tracking software (https://aircrasher.livefpv.com/live/scoring/) for drone races. But I can't. I think it's a websocket, but I don't know how to retrieve information from it. I tried curl, I tried the "ultimate-web-scraper" from GitHub (https://github.com/cubiclesoft/ultimate-web-scraper). I tried a code example from another post from here (PHP simple web socket client) but I'm not able to get this number. Is it imposible to get this number (with php)?
This is what I tried so far with the help of "ultimate-web-scraper" (https://kleesit.de/beta/livetime/webscraper/test.php):
<?php
require_once "support/web_browser.php";
require_once "support/tag_filter.php";
// Retrieve the standard HTML parsing array for later use.
$htmloptions = TagFilter::GetHTMLOptions();
// Retrieve a URL (emulating Firefox by default).
$url = "https://aircrasher.livefpv.com/live/scoring/";
$web = new WebBrowser();
$result = $web->Process($url);
// Check for connectivity and response errors.
if (!$result["success"])
{
echo "Error retrieving URL. " . $result["error"] . "\n";
exit();
}
if ($result["response"]["code"] != 200)
{
echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
exit();
}
// Get the final URL after redirects.
$baseurl = $result["url"];
// Use TagFilter to parse the content.
$html = TagFilter::Explode($result["body"], $htmloptions);
// Find all anchor tags inside a div with a specific class.
// A useful CSS selector cheat sheet: https://gist.github.com/magicznyleszek/809a69dd05e1d5f12d01
echo "All the URLs:\n";
$result2 = $html->Find("div.someclass a[href]");
if (!$result2["success"])
{
echo "Error parsing/finding URLs. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
// Faster direct access.
echo "\t" . $html->nodes[$id]["attrs"]["href"] . "\n";
echo "\t" . HTTP::ConvertRelativeToAbsoluteURL($baseurl, $html->nodes[$id]["attrs"]["href"]) . "\n";
}
// Find all table rows that have 'th' tags.
// The 'tr' tag IDs are returned.
$result2 = $html->Filter($html->Find("tr"), "th");
if (!$result2["success"])
{
echo "Error parsing/finding table rows. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
echo "\t" . $html->GetOuterHTML($id) . "\n\n";
}
?>
This is what I tried with CURL and the help of a stackoverflow post (https://kleesit.de/beta/livetime/test2.php):
<?php
// random 7 chars digit/alphabet for "t" param
$random = substr(md5(mt_rand()), 0, 7);
$socket_server='https://aircrasher.livefpv.com/live/scoring/';
// create curl resource
$ch = curl_init();
//N°1 GET request
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server,
CURLOPT_RETURNTRANSFER => TRUE,
// since it is TRUE by default we should disable it
// on our localhost, but from real https server it will work with TRUE
CURLOPT_SSL_VERIFYPEER => FALSE
]);
// $output contains the output string
$output = curl_exec($ch);
$output=substr($output, 1);
echo $socket_server;
// server response in my case was looking like that:
// '{"sid":"4liJK2jWEwmTykwjAAAR","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}'
var_dump($output);
$decod=json_decode($output);
// setting ping Interval accordingly with server response
$pingInterval = $decod->pingInterval;
//N°2 POST request
$socket_server_with_sid = $socket_server.'&sid='.$decod->sid;
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_POST => TRUE,
CURLOPT_TIMEOUT_MS => $pingInterval,
// 4 => Engine.IO "message" packet type
// 0 => Socket.IO "CONNECT" packet type
CURLOPT_POSTFIELDS => '40'
]);
$output = curl_exec($ch);
// ok
var_dump($output);
// Pervious 2 requests are called "hand shake" now we can send a message
// N°3 socket.emit
if ($output==='ok') {
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_TIMEOUT_MS => $pingInterval,
CURLOPT_POST => TRUE,
// 4 => Engine.IO "message" packet type
// 2 => Engine.IO "EVENT" packet type
CURLOPT_POSTFIELDS => '42["chat message","0devhost message 10"]'
]);
$output = curl_exec($ch);
// ok
echo $output.'<br/>';
echo $socket_server_with_sid;
}
// close curl resource to free up system resources
curl_close($ch);
?>
I am trying to get the speed limit using the OSM through php. But, I am unable to do that because I am getting the message as written below:
The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.
What could be the problem? Below is my php file.
Note: the code is still incomplete, I'm for now testing if I am able to access the OSM database.. But I cant. I hope someone could point me to the right direction..
<?php
$lat = 24.32633;
$lng = 54.58061;
$latm = -0.00015 + $lat;
$latp = 0.00015 + $lat;
$lngm = -0.00015 + $lng;
$lngp = 0.00015 + $lng;
//$json_url = 'http://overpass-api.de/api/interpreter?data=[out:json];node(24.326180, 54.580460,24.336580, 54.580860);way(bn);(._;>;);out;';
$json_url = 'http://overpass.osm.rambler.ru/cgi/interpreter';
$data = '<query type="way"> <bbox-query s="' . $lngm . '" w="' . $latm . '" n="' . $lngp . '" e="' . $latp . '"/> <!--this is auto-completed with the current map view coordinates.--> </query> <print/>';
$ch = curl_init( $json_url );
$options = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch);
echo curl_exec($ch);
/*$resultArr = explode("<",$result);
foreach ($resultArr as $val) {
$temp = explode('"', $val);
//check the size of the array, if it is == 5, then do
if ($temp[1]=="maxspeed")
$speedlimit=$temp[3];
}
echo '{"speedlimit": "120"}'; */
?>
Your bounding box is quite small and there's simply no data available in OpenStreetMap for your bounding box. That why you get the following almost empty, but valid result:
<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="Overpass API">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2015-06-06T08:10:03Z"/>
<bounds minlat="54.5805" minlon="24.3262" maxlat="54.5808" maxlon="24.3265"/>
</osm>
I would highly recommend to try different options in overpass turbo first to get more familiar with Overpass API. Please check the following link as a starting point: http://overpass-turbo.eu/s/9MQ - it's also restricted to highways with a maxspeed tag (that's what you're looking for, right?).
For illustration purposes, here's a screenshot with your tiny bounding box in the middle:
I am pretty new to php so I'm having trouble with POSTing.
I am trying to transfer information between 2 php files where send_var.php sends a command by POST and get_var.php executes some data manipulation and returns the response.
The send_var.php is as follows:
<?php
$url = "./get_var.php";
$fields = array('response' => "323243");
$data = http_build_query($fields);
// echo $data."<br />";
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: text/html\r\n",
'content' => $data
),
));
$out = file_get_contents($url, false, $context);
echo "Info from get_var : " . $out;
?>
And the get_var.php is :
<?php
$arg1 = isset($_POST['response']) ? $_POST['response'] : null;
if($arg1 == '')
{
echo "No Command! ";
}
if($arg1 != "")
{
echo $_POST['response'];
}
else
{
$_POST['response'] = "123456";
echo $_POST['response'] . " end of get_var";
}
?>
This code was extracted from other examples on stack overflow. The only output I get is "Info from get_var :"
Obviously I'm missing some pretty fundamental knowledge. If someone can help it would be much appreciated. I'm executing this under XAMPP.
In order to run a PHP script, you have to access it through the webserver. So the URL needs to be an http: URL, not just a filename:
$url = "http://localhost/path/to/get_var.php";
If you just use a filename, file_get_contents() will just return the PHP source code, it won't run it.
Also, your Content-type header is wrong, it should be application/x-www-form-urlencoded, not text/html (that's the content type of the response, your context specifies the type of the POST data).
im trying to simulate a webservice post request via my local machine using PHP, and im getting some problems.
First of all, I have a php file that is sending an xml file via Post, inside an array:
<?php
$xml = file_get_contents('localstorage.xml');
$url = 'http://127.0.0.1/projects/My_webservice/rebreFitxer1.php';
$post_data = array('xml' => $xml, );
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
?>
Then in the other side i have another php file that loads the xml content and writes it on a xml file.
<?php
header('Content-type: text/xml');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$postText = file_get_contents('php://input'); // load the content loaded via POST
$postText = utf8_encode($postText);
$datetime = date('ymdHis');
$xmlfile = "myfile" . $datetime . ".xml"; //new file name
$FileHandle = fopen($xmlfile, 'w') or die("can't open file");
// open the new file in writing mode
fwrite($FileHandle, $postText);
fclose($FileHandle);
?>
What i get from this is a bad formed xml wich i tried to convert encoding but nothing seems to operate.
Here's what i get:
xml=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%0A%3CXml...........etc
---^
It seems that symbols "< >" are not well written--> Nom%3ERetard%3C%2FNom%3E%0A++++++%3C
but i dont know how to fix it
I'm new on php and im sure that there's something i've done bad...
Thanks in advance
Your XML should be stored in $_POST["xml"] variable. So you can try:
<?php
$postText = $_POST["xml"];
?>
So i am trying to parse data from an XML url and insert it into a table using php, which can be seen here, (please keep in mind there are more products than displayed on this page, i am not trying to get it for just this Product,the code below shows how i am parsing all products) but i keep getting the following errors:
[EDITED]
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/" . urlencode($entry['family']) . "/" . urlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
[NEW ERRORS]
So i have fixed the error:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E Series/AC Adapter/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/svn/dev.comp/Asus.php on line 82
by using urlencode as shown in my code above
This warning below isnt finding the values for the url:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR///04G265003580/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
as you can see after, 44/EUR there are three forward slashes with no data?? How would i resolve this??
The remote server appears to use the Accept HTTP header to choose the output format. With PHP default options it sends back JSON instead of XML:
<?php
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null');
... prints:
{"Categories":[{"Brand":null,"Fami...
To specify an Accept header you need to retrieve the data with some other function, e.g.:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
)
)
);
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null', false, $context);
... prints:
<?xml version="1.0" encoding="utf-8"?><ProductCategory ...
Tweak it to your exact needs, I just copied the header from my browser.
Here's a code snippet that shows you how to get the values for strPartNumber, strDescription and Brand for all the products in that JSON data:
<?php
$url = 'http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null';
$json = file_get_contents($url);
// Decode the JSON data as a PHP array
$data = json_decode($json, true);
if (!empty($data['Products'])) {
foreach ($data['Products'] as $id => $product) {
echo "Product #{$id}\n";
echo "Part number: {$product['strPartNumber']}\n";
echo "Description: {$product['strDescription']}\n";
echo "Brand: {$product['Brand']}\n\n";
}
}
Output:
Product #0
Part number: 04G265003580
Description: POWER ADAPTER 65W19V 3PIN
Brand: Asus
Product #1
Part number: 14G110008340
Description: POWER CORD 3P L:80CM,TW(B)
Brand: Asus