I am using couchDB to get a UUID so that I can send a new document to the database.
In order to get this UUID, I use a curl statement:
function getUUID(){
$myCurlSubmit = curl_init();
curl_setopt($myCurlSubmit, CURLOPT_URL, 'http://localhost:5984/_uuids');
curl_setopt($myCurlSubmit, CURLOPT_HEADER, 0);
$response = curl_exec($myCurlSubmit);
curl_close($myCurlSubmit);
return $response;
}
This returns the expected result:
{"uuids":["af09ffd3cf4b35c2d94d1ed755000fb8"]}
However, the following json_decode fails:
print_r('No match, creating new document.');
$uuid = json_decode(trim(getUUID()));
var_dump(json_last_error());
The error printed is: 'int(0)' (not in quotes.), and $uuid is a json string still.
Help appreciated Thank you!
EDIT:
var_dump($uuid) = int(1)
EDIT:
var_dump(getUUID()) = {"uuids":["af09ffd3cf4b35c2d94d1ed755000fb8"]}\n1
Is there any reason why I would have a trailing one, and /n on my json??
EDIT:
The problem was with curl, look at the answer below!
The problem lies in the use of curl in the getUUID() function.
You must set CURLOPT_RETURNTRANSFER, otherwise curl_exec will just echo the result, while returning 1 (as you see).
See for example this comment in the curl_exec manual: http://www.php.net/manual/de/function.curl-exec.php#13020
Related
Hey so I'm having a slight dilemma with getting the contents of a file using a variable.
So to explain the code below a little, the respform fetches JSON array all ok. And the results url when echo'd displays like a normal URL that when viewed displays JSON data. Then I want to fetch JSON data from the second URL. If I use this variable in file_get_contents nothing happens. If I simply create a variable $url = '' and type the same address it works fine.
I've var dumped the $resulturl variable that I'm using and it is a string(56). I've tried using json_encode and it becomes a string(64). What sort of data does it need to be to be accepted into the file_get_contents.
$resp = file_get_contents($url, FALSE, $context);
$respform = json_decode($resp, TRUE);
$resulturl = $respform['resultsUrl'];
$data = file_get_contents($resulturl, FALSE);
$insta_array = json_decode($data, TRUE);
print_r($insta_array);
Hope someone can help, Thanks!
$resulturl apparently contains a JSON-encoded URL. You need to do:
$resulturl = json_decode($respform['resultsUrl']);
I know there are a lot of topics out there concerning this problem, but I've spend the last hours trying various approaches an I'm nowhere close to the solution. So here it goes ...
This is my jquery:
$.post('inc/app_json_f.php',{params:priv_params}, function (data) {
console.log(data);
// displays: \u00e2\u0082\u00ac instead of €
data = JSON.parse(data);
console.log(data);
// displays: â¬â¬ instead of €
}
This is my php (the app_json_f.php page):
$qry = 'select ... from ... where ...';
$data = $db->do_select($qry);
echo json_encode(f_utf8_json($data));
The f_utf8_json function will check the $data and convert every value with utf8_encode().
At this moment, the echo json_encode(...) will display the following in the console:
\u00e2\u0082\u00ac
Whereas I would like to see the € sign.
The data comes from a MySQL database which has collation utf8_general_ci. PHP's charset is UTF-8.
Any suggestions?
for send file using curl you need to use this working code.
if(!empty($postfields['image'])){
$file_name_with_full_path = $postfields['image'];
if (function_exists('curl_file_create')) { // php 5.6+
$cFile = curl_file_create($file_name_with_full_path);
} else { //
$cFile = '#' . realpath($file_name_with_full_path);
}
$postfields['fileToUpload'] = $cFile;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result=curl_exec ($ch);
curl_close ($ch);
User curl_file_create
When using json_encode(), include JSON_UNESCAPED_UNICODE as the second argument so that you don't get \u0123 type codes, but instead get UTF-8.
The hex for UTF-8 encoding of € is E2ACE2AC. (Ditto for MySQL's utf8 and utf8mb4.)
If you get €, then you have "Mojibake".
If you take UNHEX(E2ACE2AC) and treat it as any of cp1250, cp1256, cp1257, latin1, latin5, latin7, you get â¬â¬. It sounds like you are compounding errors to get there.
See the "best practices" and other debugging tips here:
Trouble with utf8 characters; what I see is not what I stored
By removing the f_utf8_json function (the one that converts the values to utf8 with utf8_encode()), everything works ok. Strange, because I added this function earlier in the project because it was necessary to get the right results. I have to double check, but possibly another database setting was the cause of this.
Problem solved.
I am trying to update my API with an update curl function but am struggling to work out why it isn't working
The areas where it may be wrong is key($id) I want it to
extract the ID column based on the key value for the ID array.
$URL I want to create the URL based on the const variables plus the resource name plus the value of the ID array that has been passed through rawurlencode.
So far this is my update code, but am wondering what area is wrong.
I can provide more info if needed and appreciate any help, thanks
<?php
function update(array $id,array $vaules, $resourcename)
$jsonData = json_encode($vaules);
key($id);
$url = DOMAIN.FOLDER.APIPATH.$resourcename.rawurlencode("/".$id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array ('content-type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,PUT);
curl_setopt($ch,CURLOPT_POSTFIELDS,$jsonData);
curl_exec($ch);
curl_getinfo(CURLINFO_HTTP_CODE);
}
The function key() returns the current key in an array (according to the internet pointer). Right now you're not doing anything with it, you're calling the function and not assigning it anywhere.
Did you mean to write: rawurlencode("/".key($id).$vaules);?
As your code is right now, assuming $id is an array, you're trying to convert an array into a string, which I doubt is what you want.
I want to get information about a channel, is it online at the moment or not:
$stream_list = ...;
$mycurl = curl_init();
curl_setopt ($mycurl, CURLOPT_HEADER, 0);
curl_setopt ($mycurl, CURLOPT_RETURNTRANSFER, 1);
//Build the URL
$url = "http://api.justin.tv/api/stream/list.json?channel=" . $stream_list;
curl_setopt ($mycurl, CURLOPT_URL, $url);
$web_response = curl_exec($mycurl);
but thats always return with an empty array. I saw many example based on it - mine wont work, what am I doing wrong?
An empty array probably means nothing was found with the stream list you provided.
I used http://api.justin.tv/api/stream/list.json?channel=beyondthesummit,towelliee and was able to get an array from the API, and then I used http://api.justin.tv/api/stream/list.json?channel=foobar and got an empty JSON array back.
I'd make sure $stream_list has the value you expect. And if it does, try removing the channel filter completely to see if you get results.
It returns an empty array if the channel is not live.
How can I query a particular website with some fields and get the results to my webpage using php?
let say website xyz.com will give you the name of the city if you give them the zipcode. How can I acehive this easliy in php? any code snap shot will be great.
If I understand what you mean (You want to submit a query to a site and get the result back for processing and such?), you can use cURL.
Here is an example:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
?>
You can grab the Lat/Long from this site with some regexp like this:
if ( preg_match_all( "#<td>\s+-?(\d+\.\d+)\s+</td>#", $output, $coords ) ) {
list( $lat, $long ) = $coords[1];
echo "Latitude: $lat\nLongitude: $long\n";
}
Just put that after the curl_close() function.
That will return something like this (numbers changed):
Latitude: 53.5100
Longitude: 60.2200
You can use file_get_contents (and other similar fopen-class functions) to do this:
$result = file_get_contents("http://other-site.com/query?variable=value");
Do you mean something like:
include 'http://www.google.com?q=myquery'; ? or which fields do you want to get?
Can you be a bit more specific pls :)
If you want to import the html to your page and analyze it, you probably want to use cURL.
You have to have the extensions loaded to your page (it's usually part of PHP _ I think it has to be compiled in? The manual can answer that)
Here is a curl function. Set up your url like
$param='fribby';
$param2='snips';
$url="www.example.com?data=$param&data2=$param2";
function curl_page($url)
{
$response =false;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_FAILONERROR,true);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$page_data=curl_page($url);
Then, you can get data out of the page using the DOM parsing or grep/sed/awk type stuff.