-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.

1
  • 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.. Commented Dec 18, 2012 at 12:44

2 Answers 2

1
$jsonArray = json_encode(array);

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

Sign up to request clarification or add additional context in comments.

1 Comment

Got there about 5 seconds before me :)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.