extract data into json
I retrieved MySQL data from three tables in XML using PHP:
$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-&g开发者_如何学Pythont;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;
?>
This works perfectly, but now I want to retrieve that data in JSON. I retrieved data from one table using JSON, but how to retrieve the same data from these three tables using JSON instead of XML?
Create arrays in PHP and use json_encode()
on your structure.
精彩评论