Unexpected JSON output on HTTP request - php

I am currently trying to get a simple HTTP JSON response from a website.
When I look at the page when I use Google Chrome:
{"columns":[{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"decimal","size":17,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":4,"nullable":true},{"name":"xx","dataType":"varchar","size":2,"nullable":true},{"name":"xx","dataType":"varchar","size":20,"nullable":true}],"rows":[["xxxxx","xxxx/xxxx","xxxx","Yacouba","5xx","xx","xxxxx"]]}
However when I use the following php code:
<?php
$json_url = "xxxx"; // url is something else but privacy reasons etc
// Initializing curl
$ch = curl_init();
// Configuring curl options
$options = array(
CURLOPT_URL => $json_url,
CURLOPT_POST => FALSE
);
// Setting curl options
curl_setopt_array($ch, $options);
// Getting results
$result = curl_exec($ch); // Getting jSON result string
curl_close($ch);
json_decode($result);
var_dump($result);
and then the output is as fallows:
‹ì½`I–%&/mÊ{JõJ×àt¡€`$Ø#ìÁˆÍæ’ìiG#)«*ÊeVe]f#Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ñGÓª\/–ÍG¾÷‹?Zf‹ü£Gͪ¦)òú÷/³I^~4úh–µÙ›ë¾ºÌêé<«éæø}°wÿþè£åº¤¦%ýÙÖëü—Œz€–Y¶ø8—U=ËëbyñûÏòIÑæëú÷¯Vù²i³l9Ïòi±ÈJx÷Á&ü´E°iëŒÞÕyóû¯¦¿ÿ²n6CÛ¿=¬²½ ØÞmFXçeÖ9¡v°´ï>ª«+pÈ÷>ÚýôÓ{Ôúm±l&y}‘/ïþ>Ù´ZO2úpoow´»C¿¹ÏîïìJ?žŸÐ?;;;û÷÷?Ýûèûßÿ%ÿOÿÿzbool(true)
What could the problem be?

I fix it! :D with:
CURLOPT_ENCODING => ''

Related

curl_setopt_array for USPTO records returns "Internal Sever Error1"

I'm trying to test retrieving an USPTO dataset for a number of records for oa_rejections using their open API:
https://developer.uspto.gov/ds-api-docs/index.html?url=https%3A//developer.uspto.gov/ds-api/swagger/docs/oa_rejections.json/v2#!/oa_rejections/perform_search
I have made the following php script. It ends up displaying just "Internal Server Error1":
<?
$params=['criteria'=>'*%3A*', 'start'=>'100', 'rows'=>'3'];
$defaults = array(
CURLOPT_URL => 'https://developer.uspto.gov/ds-api/oa_rejections/v2/records',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
$contents = curl_exec($ch);
echo $contents;
?>
Is there anything vital or obvious that I'm missing, or perhaps I cannot use this syntax at all to retrieve this data?

CartoDB - SQL API - Post request with php

In my app I'd like to send some small amount of data to my cartodb-table with my php-script.
I would like to use the SQL-API. My app parse the data in the form like:
https://{account}.cartodb.com/api/v2/sql?q=INSERT INTO test_table (column_name, column_name_2, the_geom) VALUES ('this is a string', 11, ST_SetSRID(ST_Point(-110, 43),4326))&api_key={Your API key}
I tried several functions http_get, file_get_contents, http_request but nothing pass the data to my account. Put when I copy/paste the URL and open in the browser, everything is added.
What's the right function? There so many different ones... PHP-HTTP-Functions
EDIT
With the code from this solution I get this error, when I print out the response:
{"error":["syntax error at end of input"]}
within the browser I get this:
{"rows":[],"time":0.038,"fields":{},"total_rows":1}
my request code right now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fullurl);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
print($response);
Found the result: with CURLOPT_POST => 1 it works!
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "https://".$cartodb_key.".cartodb.com/api/v2/sql",
CURLOPT_USERAGENT => 'Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
api_key => $api_key,
q => "INSERT INTO spot (".implode (", ", array_keys($data)).") VALUES (".implode (", ", $data).")"
)
));
$response = curl_exec($ch);
curl_close($ch);

PHP Creating a request in code

I need to create a new PHP HTTP Request within my code. It returns a json-encoded array of data. How do I create a new HTTP Request and not redirect to that location?
Thanks.
assuming you're trying to get a json file and put it into an array:
$content = file_get_contents('http://www.example.com/test.json');
$json_array = json_decode($content);
print_r($json_array)
This is what you are looking for: http://codular.com/curl-with-php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://stackoverflow.com'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//For testing only
print_r('<pre>');
print_r($resp);die();

How to proxy another page in PHP

I'm looking for the fastest and easiest way to proxy a page in PHP. I don't want the user to be redirected, I just want my script to return the same content, response code and headers as another remote URL.
echo file_get_contents('proxypage');
Would that work?
EDIT:
First answer was a bit short, and I don't believe it will handle headers as you would like.
However you can also do this:
function get_proxy_site_page( $url )
{
$options = [
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$remoteSite = curl_exec($ch);
$header = curl_getinfo($ch);
curl_close($ch);
$header['content'] = $remoteSite;
return $header;
}
This will return you an array containing lots of information on the remote page. $header['content'] will have both the content of the website and the headers, $header[header_size] will contain the length of that header so you can use substr to split those up.
Then it's just a matter of using echoand header to proxy the page.
You can use the PHP cURL functions to achieve this functionality:
http://www.php.net/curl
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$urlContent = curl_exec($ch);
From this point, you would grab the response header information using http://www.php.net/curl-getinfo. (There are several values you can grab, all listed in the documentation).
// Check if any error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
header('Content-Type: '.$info['content_type']);
echo $urlContent;
}
Make sure to close out the cURL handle.
// close cURL resource, and free up system resources
curl_close($ch);
You can get the html of the next page with curl, and then echo the response.

DOMDocument load on a page returning 400 Bad Request status

I'm trying to use the Last.fm API for an application I'm creating, but am having some problems with validation.
If an API request gives an error it returns a code and message in the response XML like this:
<lfm status="failed">
<error code="6">No user with that name</error>
</lfm>
However, the request also returns an HTTP status of 400 (or in some cases 403) which DOMDocument considers an error and so then refuses to parse the XML.
Is there any way round this, so that I can retrieve the error code and message?
Thanks
Pete
A solution could be to separate your manipulations in two steps :
First, get the XML string, using curl, for example
Then, work on that string with DOMDocument.
There is an example of how you can use curl on the curl_exec manual page ; adding a few useful options, you could use something like this, I suppose :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "YUR_URL_HERE");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml_string = curl_exec($ch);
curl_close($ch);
// You can now work with $xml_string
And, for more options (there are a lot of them ^^ ), you can take a look to the manual page of curl_setopt.
I resolved the issue by using try & catch. If it can help someone
function getXML($xml) {
$dom = new DomDocument();
try {
#$dom->load($xml); // The '#' is necessary to hide error if it's a error 400 - Bad Request
$root = $dom->documentElement;
return $root;
}
catch(Exception $e)
{
return false;
}
}
You can always get the response with some other function like file_get_contents and then parse the XML with DOMDocument::loadXML
Edit:
http://www.php.net/manual/en/domdocument.load.php#91384
The Function:
function getAlbum($xml,$artist,$album)
{
$base_url = $xml;
$options = array_merge(array(
'user' => 'YOUR_USERNAME',
'artist'=>$artist,
'album'=>$album,
'period' => NULL,
'api_key' => 'xYxOxUxRxxAxPxIxxKxExYxx',
));
$options['method'] = 'album.getinfo';
// Initialize cURL request and set parameters
$ch = curl_init($base_url);
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://ws.audioscrobbler.com/2.0/',
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $options,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array( 'Expect:' ) ,
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
));
$results = curl_exec($ch);
unset ($options);
return $results;
}
Usage:
// Get the XML
$xml_error = getAlbum($xml,$artist,$album);
// Show XML error
if (preg_match("/error/i", $xml_error)) {
echo " <strong>ERRO:</strong> ".trim(strip_tags($xml_error));
}

Categories