将数据提取到json中

时间:2010-12-03 07:58:55

标签: php

我使用PHP从XML中的三个表中检索MySQL数据:

$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);

$doc = new DomDocument('1.0');

$root = $doc->createElement('recipes');
$root = $doc->appendChild($root);

while($row = mysql_fetch_assoc($resouter)){

$outer = $doc->createElement($table_first);
$outer = $root->appendChild($outer);

 foreach ($row as $fieldname => $fieldvalue) {
    $child = $doc->createElement($fieldname);
    $child = $outer->appendChild($child);
    $value = $doc->createTextNode($fieldvalue);
    $value = $child->appendChild($value);
  }// foreach
 //while

  $table_second='instructions';
$query="SELECT instructions.instruction_id,instructions.instruction_text FROM $table_second where rec_id = ".$row['rec_id'];
$resinner=mysql_query($query, $conn);

$inner = $doc->createElement($table_second);
    $inner = $outer->appendChild($inner);
 while($row1 = mysql_fetch_assoc($resinner)){

    $inner1=$doc->createElement('instruction');
    $inner1=$inner->appendChild($inner1);

    foreach ($row1 as $fieldname => $fieldvalue) {
        $child = $doc->createElement($fieldname);
        $child = $inner1->appendChild($child);
        $value = $doc->createTextNode($fieldvalue);
        $value = $child->appendChild($value);
    } // foreach
 }// while

$table_third='ingredients';

$query="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM $table_third where rec_id = ".$row['rec_id'];
$resthird=mysql_query($query, $conn);


 $inner=$doc->createElement($table_third);
    $inner=$outer->appendChild($inner);

while($row=mysql_fetch_assoc($resthird)){
$inner2=$doc->createElement('ingredient');
    $inner2=$inner->appendChild($inner2);
foreach($row as $fieldname=> $fieldvalue)
    {
        $child=$doc->createElement($fieldname);
        $child=$inner2->appendChild($child);
        $value=$doc->createTextNode($fieldvalue);
        $value=$child->appendChild($value);
}
}
}

mysql_close($conn);
$xml_string = $doc->saveXML();
echo $xml_string;
?>

这很好用,但现在我想用JSON检索那些数据。我使用JSON从一个表中检索数据,但是如何使用JSON而不是XML从这三个表中检索相同的数据?

1 个答案:

答案 0 :(得分:0)

在PHP中创建数组并在结构上使用json_encode()