Euro symbol is shown as \u00e2\u0082\u00ac and â¬â¬ - php

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.

Related

PHP Update with Curl Please

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.

Part of string missing after urldecode() in php

I have an encoded string (it is too long to be posted here). When I use different utilities for decoding the string (http://www.the-art-of-web.com/javascript/escape/) the string looks perfect after urldecode(). However, when I actually pass the string through urldecode() in my php file on my testing environment the first 100 or so characters are missing. I cannot figure out why. I have tried both urldecode and rawurldecode. If you want to see the string I am trying to process you can make a GET request against this url http://pacific-wave-7885.herokuapp.com/api/opencart the string I am working with is the "contents" value of the JSON object
What i am trying to accomplish:
I want to make a php file that calls the above api address, gets the contents from the JSON object, decodes the string and parses the code.
here is what I have tried:
function utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://pacific-wave-7885.herokuapp.com/api/opencart', false, $context);
$contents_decode = utf8_urldecode($file);
echo $contents_decode;
You can see with this code that the "contents" starts with "language->load('shipping/usps')" and is missing the first 100 or so characters of that part of the string.
I have also tried this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://pacific-wave-7885.herokuapp.com/api/opencart");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = json_decode($output, true);
$contents = $data[0]['contents'];
$contents_decode = urldecode($contents);
echo $contents_decode;
curl_close($ch);
This also produces the same result - part of the beginning of the string is missing.
to reiterate: if you grab the encoded string straight from the JSON object and use an online decoding tool the string looks great, but once it is passed through urldecode() in my php file the first part of the string is missing characters.
If anyone can see what I am missing I would be so grateful.
Just fyi: My php environment is the latest version of XAMPP with php5 and the JSON object is coming from a NODE server with express.js.
If anyone has a better idea of how I can pass php code as a string from a Node server to a PHP server and then parse it I would be open to that as well.
I'm going to make two assumptions:
It's showing up starting at language->load('shipping/usps');
You are viewing the returned string in your browser.
Good news is that you aren't missing any characters! The browser is simply misinterpreting the tags -
<?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this->
The browser is trying to make sense of it - it doesn't know this is PHP, it thinks it is HTML. It sees < and thinks "oh cool, beginning of an HTML tag." And then it sees ? and it just tries to figure out what kind of malformed tag this is, and then it see's -> and it decides it must be an HTML comment, so it parses it as:
<!--?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this--->
Change echo $contents_decode; to echo "<textarea>" . $contents_decode . "</textarea>" and you'll see the full string.
Why not just return the data (instead of a PHP block in the contents) and have your PHP class on the receiving end decode the JSON and complete the logic.
If you are insisting on getting the PHP block back...it might be easier to just return a JSON response from node/express and use json_decode to pull it into an array. In playing with this the only way I could make your PHP block JSON friendly was to escape it then encodeURIComponent.
<?php
$jsonString = '{
"name":"usps.php",
"version":1,
"platform":"opencart",
"contents":"%253C%253Fphp%250Aclass%2520ModelShippingUsps%2520extends...57D%250A%2509%2509%257D%250A%250A%2509%2509return%2520%2524method_data%253B%250A%2509%257D%250A%257D%250A%253F%253E",
"_id":"53c40942bddf820200000007",
"__v":0
}
';
$jsonArr = json_decode( $jsonString, true);
var_dump( urldecode( urldecode( $jsonArr["contents"] ) ) );
?>

Formatting long structured text string from Jira Atlassian issue url in php

Im wondering if there is an easy way to access the information in a huge string i have, the string is structured, for the purpose of people reviewing it i put line breaks and space but this is just one huge single line of text that's returned:
First this is how i access the Jira API:
$username = 'xxx';
$password = 'xxx';
$url = 'https://xxx.atlassian.net/rest/api/2/Issue/Bug-5555';
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$issue_list = (curl_exec($curl));
echo $issue_list;
Now that returns a huge string which when broken down looks like this:
{"expand":
"renderedFields,names,schema,transitions,operations,editmeta,changelog",
"id":"16935",
"self":"https://xxx.atlassian.net/rest/api/2/issue/16935",
"key":"xx-5555",
"fields":
{"summary":"Dialog boxes shouldn't be on top.",
"progress":
{"progress":0,
"total":0
},
"timetracking":{},
"issuetype":
{"self":"https://xxx.atlassian.net/rest/api/2/issuetype/1",
"id":"1",
"description":"A problem which impairs or prevents the functions of the product.",
"iconUrl":"https://xxx.atlassian.net/images/icons/bug.gif",
"name":"Bug",
"subtask":false
},
"timespent":null,
"reporter":
{"self":"https://xxx.atlassian.net/rest/api/2/user?username=xxx%40xxx.com",
"name":"xxx#xx.com",
"emailAddress":"xxx#xxx.com",
"avatarUrls":{"16x16":"https://xxx.atlassian.net/secure/useravatar?size=small&avatarId=10122",
"48x48":"https://xxx.atlassian.net/secure/useravatar?avatarId=10122"},
"displayName":"xxx",
"active":true
},
"created":"2012-08-25T18:39:27.760-0600",
"updated":"2012-08-31T16:47:38.761-0600",
"priority":
{"self":"https://xxx.atlassian.net/rest/api/2/priority/6",
"iconUrl":"http://dl.dropbox.com/u/xxx/3-green.png",
"name":"3 - Medium Priority",
"id":"6"
},
"description":"\"loading \" dialog is always on top, so is the \"Updating database\" dialog.\r\n\r\n\r\nThis is annoying. It shouldn't be on top and/or you should be able to easily minimize the window.",
"issuelinks":[], etc etc etc
Now im a basic php user so please try and keep the replies simplistic if possible, before i go down the route of parsing the whole document which will be difficult for me as im not familiar with parsing i was wondering if there was an easy way to access the values.
what im thinking is something like this:
foreach($issue_list->issues as $issue) {
echo "summary" . $issue->summary;
echo "updated" . $issue->updated;
echo "created" . $issue->created;
echo "description" . $issue->description;
}
Now this might be wishful thinking but i seen an article where i guy done something similar but i cant figure it out, here is the article:
http://www.lornajane.net/posts/2012/using-jiras-rest-api-to-create-a-dashboard
Also if it is possible, how would i access the reporter > displayName value since that's 2 indents deep, would it be $issue->reporter->displayName;
Finally one quick other question, if im echoing the description, how do i get it to obey the /r/r/r/r/r/n and /" so it prints it out with line breaks and removes those special characters?
This looks like a JSON (JavaScript Object Notation - more info here) string, you could probably use json_decode (documented here) to convert it into a PHP object and then easily index it.
I don't have your full string but you can probably try something along the lines of:
$jiraIssue = json_decode($theString);
echo $jiraIssue["id"];
Now, since objects are contained inside of objects, you'll probably have to go through "fields" before you can access "summary".
You can pass true as a second parameter if you'd prefer to deal with arrays instead of objects.

Json_Decode not Decoding my JSON

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

website query, php

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.

Categories