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) ;

?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top