-5

Possible Duplicate:
How to generate json using php?

I want to generate a JSON file using PHP. Now I'm generating a XML file:

public function CreateXML($array){

/*$array contains several arrays and look like this:
  [0] => Array( [0] => Jonas [1] => Anne [2] => Peter)
  [1] => Array( [0] => Andersen [1] => Berg [2] => Jobs)
  [2]......*/   

$newArray = array2();
for($i = 0; $i <= count($array[0]); $i++) {
    $newArray[] = array2($array[0][$i], $array[1][$i], $array[2][$i]);

}

$xmlDoc = new DOMDocument("1.0", "iso-8859-1");

$root = $xmlDoc->appendChild(
          $xmlDoc->createElement("Contacts"));


  foreach($newArray as $row) {

  $tag = $root->appendChild(
              $xmlDoc->createElement("Contact"));

    $tag->appendChild(
       $xmlDoc->createElement("Firstname", $row[0]));

    $tag->appendChild(
       $xmlDoc->createElement("Lastname", $row[1]));
     .......
      }

 $xmlDoc->formatOutput = true;
 echo $xmlDoc->saveXML();
}

//output
<Contacts>
  <Contact>
    <Firstname>Jonas</Firstname>
    <Lastname>Andersen</Lastname>
    .......
  </Contact>
 ......
</Contacts>

So my question is, how can I get the same result but instead generate JSON? This is my first time working with JSON and I just can't get it to work.

Community
  • 1
  • 1
ana
  • 475
  • 4
  • 10
  • 21
  • In Stackoverflow you should not write like this 'please show me the code or please write it for me..'..Atfirst do some research and afterthat if you face any trouble ask here..otherwise downvotes will be increased.. – Mrinmoy Ghoshal Dec 18 '12 at 12:44

2 Answers2

1
$jsonArray = json_encode(array);

Out of the box (but of course before that you should alter your array to be an associative one) :)

Lothar
  • 529
  • 1
  • 5
  • 19
0

The easiest approache would be to use the json_encode($array) function. This function returns the json representation of the array as a string. This string can be written in a file.

Andre
  • 170
  • 6