I have a php file where I am outputing json.
<?php
header('Content-Type: application/json');
?>
var data = {
"cars": [
<?php foreach ($runshowcars as $rowscar):;?>
{
"id":"<?php echo $rowscar['id'] ?>",
"name":"<?php echo $rowscar['name'] ?>"
}
],
"boats": [
<?php foreach ($runshowboats as $rowsboat):;?>
{
"id":"<?php echo $rowsboat['id'] ?>",
"name":"<?php echo $rowsboat['name'] ?>"
}
],
};
This works however the output looks like this.
var data = {
"cars": [
{
"id":"1",
"name":"Ford"
}
,{
"id":"2",
"name":"Honda"
}
]
};
I want it to look like this.
var data = {"cars": [{"id":"1","name":"Ford"},{"id":"2","name":"Honda"}]};
The only way I have found to do this is to remove the white spaces from my php file, this is obviously not an ideal solution as it makes it very hard to maintain.
How can strip out all the white spaces here?
I have seen plenty of questions like this one, How to minify php page html output? however I can't get something like this working here as my data isn't in a variable?
Why don't you collect your data into an array and encode it to json.
Like this:
$data=array('cars'=>$runshowcars, 'boats'=>$runshowboats);
print json_encode($data);
(Otherwise you return javascript, and not json. At least if you prepend the result with the var data = part.)
Just create a multi dimensional associative array and use json_encode
You can remove everything outside <?php ?> like this :
<?php
header('...') ;
echo 'var data = {' ;
echo '"cars": [' ;
foreach ($runshowcars as $rowscar)
{
echo '{' ;
echo '"id":"'.$rowscar['id']?'",' ;
echo '"name":"'.$rowscar['name'] ;
echo '}' ;
}
echo '],' ;
...
?>
Or you can try json_encode php function (wich could be a better way imo) :
<?php
$data = Array('cars'=>$runshowcars,'boats'=>$runshowboats) ;
echo 'var data = '.json_encode($data) ;
?>
Related
Hi I need to do a school assigement with a API thats generating json.
I get with $API my json. With some testing by myself I can say that the json is correct. But in the assigement it says I need to validate it with a json schema. I have the schema but I cant get it to work so it will check and validate the incomming json.
If someone sees the problem pls tell me because I cant find it.
<?php
//Json gets validated
if(isset($API))
{
?>
<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js">
var validator = require('validator');
var jsv = require('json-validator');
jsv.validate("<?php echo $API; ?>", "json_schema.json", function(err, messages)) {
if(err)
{
throw err;
}
else
{
$.getJSON("<?php echo $API; ?>", function(data)
{
var items = [];
$.each(data, function(key, val, val2) {
items.push("<li id='" + key + "'>" + val["COL 3"] + "</li>");
items.push("<br>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo(".datapanel");
});
}
}
</script>
<?php
}
?>
Replace both <?php echo $API; ?> by <?php echo str_replace('"', '\\"', $API); ?>.
Even better, you could have this process once and then echo the escaped string:
<?php
// Json gets validated
if (isset($API))
{
// escape your JSON string
$escapedAPI = str_replace('"', '\\"', $API);
?>
...
<!-- echo the escaped string -->
<?php echo $escapedAPI; ?>
...
<?php
}
?>
The issue you're facing is that currenty, when PHP echo the JSON in your Javascript, it produces something like this:
jsv.validate("[{"COL 3":"(APPLAUSE)"}, ... ]", "json_schema.json", function() { ... })
As you can see, the " from the Javascript are mixed with the one "echoed" which produce invalid Javascript. This is why you need to escape them before "echoing" your JSON.
I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>
i have the following code, but it will not work. i am trying to create a script output:
echo "<script type=\"text/javascript\"><!--\n";
echo "SLIDES = new slideshow(\"SLIDES\")\n";
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname ) {
echo 's = new slide()\n';
echo 's.src = \"http://cashbackflorida.com/wpradmin/modules/wprrets/photos/'.$result ->MLS.'/'{$fname}\n\"';
echo 's.width = \"560\"\n';
echo 's.height = \"420\"\n';
echo 's.alt = \"{$fname}\"\n';
echo 's.text = unescape(\"\")\n';
echo 's.link = \"\"\n';
echo 's.target = \"\"\n';
echo 's.attr = \"\"\n';
echo 's.filter = \"\"\n';
echo 'SLIDES.add_slide(s)\n';
}
echo '--></script>\n';
Don't do it this way. Just output the array to JavaScript and deal with it there.
var files = <?php echo json_encode($files); ?>;
You'll find the problem in your string escaping
echo 's.height = \"420\"\n';
You can't escape in single quote strings like that. So try this
echo "s.height = \"420\"\n";
You do NOT need to escape single quotes within double quotes or visa versa, but you can only get a newline character like that in a double quote string.
I would recommend HEREDOC for this kind of string writing though.
$fnamej = json_encode($fname);
echo << EOT
s.height = "420";
s.alt = $fnamej;
EOT;
I am also inclined to say that you'd be better off handling this in javascript. This may end up behaving very badly all of a sudden, and it will take up more bandwidth.
I am getting error in Firefox SyntaxError: unterminated string literal when i try to include following code:
<script>
function makeProdiv(data){
var tbl_body = "";
var tbl_row = "";
tbl_row +="<?php foreach($data as $row) {} ?>" (Error at this line)
tbl_body += tbl_row;
return tbl_body;
}
</script>
If i remove this row then error disappears.
What i am trying: I am trying to loop through the result returned from DB and display values.
Please anyone can assist?
You most likely have double quotes in the content generated by PHP. You need to escape them properly, or, providing you don't have single quotes in the PHP content, you could do:
tbl_row +='<?php foreach($data as $row) { /* ... */} ?>';
As noted in the comments, having newlines in your PHP content might also cause this issue. Remove or replace them.
Try something like this:
<?php foreach ($data as $row) { ?>
tbl_row += <?php echo json_encode(whatever); ?>;
<?php } ?>
Using json_encode() will ensure that the PHP value is correctly encoded for Javascript.
Try this:
<?php foreach($data as $row) {?>
tbl_row +=<?php echo $row;?>
<? }?>
what it contain?the
'data' that is passed to this function "makeProdiv(data)"
& $data.
I guess $data is an array of "tr" fetched from db.
i have a json object.
$json = json_decode($data,true);
it looks like-
array(5) {
["screenShareCode"]=>
string(9) "021113322"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEN5gBYi4vlIEGpk0="
["viewerUrl"]=>
string(65) "http://api.leap.com/v2/viewer/021113322?accountid=mynet"
["origin"]=>
string(3) "API"
}
alert('?php echo $json; ?>');
when i am trying to assign this into javascript variable it gives me an error saying "unterminated string constant".
You don't decode it, in PHP or JavaScript. The contents of a JSON string is a valid JavaScript literal.
<?php
...
?>
<script ...>
var data=<?php echo $data; ?>;
alert(data["screenShareCode"]);
<?php
...
Try:
alert(<?php echo json_encode($json); ?>);
or:
alert(<?php echo $data; ?>);
You're a bit confused about terminology. $data is a JSON string, $json is a PHP array that you got by decoding the JSON string.
Try the following code. I have created a php file named sample.php. We have a php array named $data. Encode that data in to json using json_endode(). That results json formatted data. Then we can assign it into a java script variable like var jsonData = <?php echo $jsonData ?>; Note that this is done inside <script> tag.
<?php
// We have some data
$data = array(
"screenShareCode"=>"021113322",
"appletHtml"=>"",
"presenterParams"=>"aUsEN5gBYi4vlIEGpk0",
"viewerUrl"=>"http://api.screenleap.com/v2/viewer/021113322?accountid=mynet",
"origin"=>"API"
);
// Convert it into json format.
$jsonData = json_encode($data,true);
?>
<script>
// Assign that json data to a java-script variable
var jsonData = <?php echo $jsonData ?>;
// To view the full data
console.log(jsonData);
// You can take a specific data like this.
alert(jsonData.presenterParams);
</script>