Php 如何从mysql的三个表中检索xml数据
我想从mysql中存储的三个表中检索xml数据。我使用了下面的代码,它工作得很好,但首先它从第一个表中检索一条记录,然后迭代到第二个表并打印整个表,然后迭代到第三个表并打印整个表,但我想打印第一个表以及第二个表(不是整个表)中的相关记录,然后从第三个表中打印,依此类推。我的代码是Php 如何从mysql的三个表中检索xml数据,php,Php,我想从mysql中存储的三个表中检索xml数据。我使用了下面的代码,它工作得很好,但首先它从第一个表中检索一条记录,然后迭代到第二个表并打印整个表,然后迭代到第三个表并打印整个表,但我想打印第一个表以及第二个表(不是整个表)中的相关记录,然后从第三个表中打印,依此类推。我的代码是 $table_first = 'recipe'; $query = "SELECT * FROM $table_first"; $resouter = mysql_query($query, $conn); $tab
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$table_second='instructions';
$query="SELECT instructions.instruction_id,instructions.instruction_text FROM $table_second";
$resinner=mysql_query($query, $conn);
$table_third='ingredients';
$query="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM $table_third";
$resthird=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
$inner = $doc->createElement($table_second);
$inner = $outer->appendChild($inner);
while($row = mysql_fetch_assoc($resinner)){
// add node for each record
$inner1=$doc->createElement('instruction');
$inner1=$inner->appendChild($inner1);
// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $inner1->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} // foreach
}// while
$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;
有一个更好的方法来完成你正在做的事情。看起来好像您使用三个不同的SQL查询和三个对数据库的调用从三个不同的表中提取数据 实现这一点的最佳方法是使用单个查询在SQL端构建表。查询稍微复杂一点(您需要连接),但是结果将更容易在您的程序中使用。您还可以避免使用DOM动态创建文档。您可以使用SQL简单地构建您的配方,将整个结果拉回来,然后简单地使用结果遍历表