문제

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