PHP json_decode does not work - php

I am trying the following code to receive JSON . However the decode does not give a result. It works for a copy of the same string with escape slashes.
<?php
$input = file_get_contents('php://input');
logToFile("post.txt",$input);
#Output: {"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}
$data = json_decode($input,true);
logToFile("post.txt",$data['version']);
#Output:Empty result
### Works
$data1 = json_decode("{\"id\":\"id1\",\"model\":\"model1\",\"version\":\"v1\",\"software\":[\"s1\",\"s2\",\"s3\"]}",true);
logToFile("post.txt",$data1['version']);
#Output:v1
function logToFile($filename,$msg)
{
$fd=fopen($filename,"a");
$str="[".date("Y/m/d h:i:s")."]".$msg;
fwrite($fd,$str."\n");
fclose($fd);
}
?>
I am using PHP 5.4. So it's not a problem in magic quotes. Any help?

I don't think the problem is with the json_decode.
$input = '{"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}';
$data = json_decode($input,true);
echo $data['version'];
Works fine.
So if you go:
echo "<pre>";
print_r( $input );
echo "</pre>";
After you get the $input from the file. Does it appear OK ?

Related

want to copy a specic text from other web in PHP

Ltes say i want to copy a text from site ( http:// www.example.com/ex )
when i open http:/ /www.example.com/ex it shows this data click here
i want to copy every text after MrsId which is in between the double quotes(means i want to copy MN4D / CN4D / MK4D / MO4D all othese four codes from example.com/ex and these codes changes daily )
and sotre in a varible eg ( $a= 'MN4D', $b='CN4D' ,$c='MK4D' ,$d='MO4D' )
then want to use it as
$first = 'http:// www.example.com/?code=';
$url = "{$first}{$a}";
$urll = "{$firsts}{$b}";
$urlll = "{$firsts}{$c}";
$urlllll = "{$firsts}{$d}";
$result = file_get_contents($url);
$results = file_get_contents($urll);
$resultss = file_get_contents($urlll);
$resultsss = file_get_contents($urllll);
echo $result;
echo $results;
echo $resultss;
echo $resultsss;
I am serching for this code from 1 month but did't get success yet.
Change the code for your needs:
<?php
$json = '{"Amrlist":[{"Amcd":"mr-pub-4925511/1986","MrsId":"MN4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"CN4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"MK4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"MO4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"}]}';
$decoded = json_decode($json, true);
//var_dump($decoded);
$url = 'http://www.example.com/?code=';
foreach($decoded{'Amrlist'} as $Amrlist) {
//print_r($Amrlist);
print $url.$Amrlist['MrsId']."\n";
//print file_get_contents($url.$Amrlist['MrsId']);
}
/**/
?>
As I can see - data has json format. So you can use json_decode to access needed fields

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

PHP; encode and decode functions produce the same output

Sanitising some user input;
function html_mysql_sanitise($data) {
if(get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
$data = htmlentities($data, ENT_QUOTES);
$data = htmlspecialchars($data, ENT_QUOTES);
return mysql_real_escape_string($data);
}
$_POST['data'] = html_mysql_sanitise($_POST['data']);
echo $_POST['data'];
echo html_entity_decode(htmlspecialchars_decode($_POST['data']));
echo html_entity_decode($_POST['data'], ENT_NOQUOTES);
echo htmlspecialchars_decode($_POST['data'], ENT_NOQUOTES);
$_POST['data'] is set to;
test<d#'!;ta>
The output of this is;
test<d#'!;ta>
test
test<d#'!;ta>
test<d#'!;ta>
Why do the last two produce the same result, and the 2nd one is part of the posted data? Since the last two seem to produce the desired result, which should I use?
Thank you.
Why re-invent the wheel... use this:
http://htmlpurifier.org/docs
Or this:
http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/index.php
Both good at exactly what you want to do.

Stackoverflow API for fetching user details returns wierd symbols

Can someone point me where am I doing it wrong. This is my code:
<?php
$link = "http://api.stackexchange.com/2.0/users/534755?site=stackoverflow";
$var = file_get_contents($link);
echo $var;
?>
And this is what I get if I run this snippet:
‹ì½`I–%&/mÊ{JõJ×àt¡€`$Ø#ìÁÍæ’ìiG#)«*ÊeVe]f#Ìíť¼÷Þ{ï½÷Þ{ï½÷º;ťN'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ñGE›/šŹ}ï´nòú÷/f=ºoÿÁýû#ù ½^å=ú¨Î/Š¦Íë|öÑè£iťgmQ-ÿYÖÒ—»{w<|¸û駣ŹfE³*³ëß™-ðÚ‹âmUfôʪ®Î‹2ÿý‹Ev/æm»zt÷îÕÕÕø¢Î.³6«ÇÓjqW~½›äû÷ïg³éÁìáù§ÓüÓÉÁäüàþÎùÎìáîÁìÓßcöY1Ë—m1­–¿°þìåçÔEť¯Ö-ãECØyàðûOçÙò"'|¯?z´ûæ*Ïß|µ¨–í£Ś}ù‹ÖYMd¡£^çYŤW‰2<nüRfMûûgÓiÞ4†€÷î}zïáîÎÁž~»¨fÅy‘ÏÜ÷{÷vöîÝ£>Šæ÷Ï«²ºÎé‹ó¬lrz§X¾u4mÚlú¶ºÌëó²ºb¢b"›»2­w—fJ®òIC³ÿû¯ë2ś²¸·“u9ÙnÚõ¬¨Ú—ÕT©ûÑI]ѯBã¨ÖË–ùfïþþÇ„â$›ÑÐùsâ¬_üÑEUζMQ^‚V÷¨M]-€¡íÿ’¯Úß¿–Áîìü’ïŹ>úEëªÍ~ÿ:_dŲX^ôæÓEöŽ€ìÄyÖ±jCŠ_òÿÿÿ”ÄÐ
Whereas this is what I get if I navigate to the given link in my browser:
{"items":[{"user_id":534755,"user_type":"registered","creation_date":1291799166,"display_name":"Nikola","profile_image":"http://www.gravatar.com/avatar/e8e455adc8d9f6ce6b8bf850f0d918d6?d=identicon&r=PG","reputation":507,"reputation_change_day":0,"reputation_change_week":0,"reputation_change_month":12,"reputation_change_quarter":57,"reputation_change_year":126,"age":26,"last_access_date":1336387120,"last_modified_date":1332302337,"is_employee":false,"link":"http://stackoverflow.com/users/534755/nikola","website_url":"http://www.lightbulb-studio.com","location":"Croatia","account_id":254997,"badge_counts":{"gold":0,"silver":3,"bronze":14},"accept_rate":100}],"quota_remaining":289,"quota_max":300,"has_more":false}
The response is gzip-compressed. You'll need to unzip it.
Try something like:
<?php
$link = "http://api.stackexchange.com/2.0/users/534755?site=stackoverflow";
$data = file_get_contents($link);
$var = gzinflate(substr($data, 10, -8));
echo $var;
?>
if you don't have gzdecode function, try to use this gzdecode

Returning JSON from PHP to JavaScript?

I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:
$json = "{";
foreach($result as $addr)
{
foreach($addr as $line)
{
$json .= $line . "\n";
}
$json .= "\n\n";
}
$json .= "}";
Basically, I need the results of the two for loops to be inserted in $json.
Php has an inbuilt JSON Serialising function.
json_encode
json_encode
Please use that if you can and don't suffer Not Invented Here syndrome.
Here are a couple of things missing in the previous answers:
Set header in your PHP:
header('Content-type: application/json');
echo json_encode($array);
json_encode() can return a JavaScript array instead of JavaScript object, see:
Returning JSON from a PHP Script
This could be important to know in some cases as arrays and objects are not the same.
There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
If you don't, here's the PECL library you can install.
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
Usually you would be interested in also having some structure to your data in the receiving end:
json_encode($result)
This will preserve the array keys as well.
Do remember that json_encode only works on utf8 -encoded data.
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
$msg="You Enter Wrong Username OR Password";
$responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

Categories