2015-08-21 3 views
0

Вот что я придумал и, похоже, работает для возврата одной записи, однако если в базе данных имеется более одной записи (wp_hud_display.id), она разбивает XML, будет «foreach» работать в цикле while? и как я могу добавить его в свой код?Как добавить MySQL foreach loop в DOMDocument XML

<?php  
// create a dom document with encoding utf8 
$domtree = new DOMDocument('1.0', 'UTF-8'); 

//database configuration 
$config['mysql_host'] = "localhost"; 
$config['mysql_user'] = "root"; 
$config['mysql_pass'] = ""; 
$config['db_name'] = "tasmanhud"; 

//connect to host 
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); 

//select database 
@mysql_select_db($config['db_name']) or die("Unable to select database"); 

//select all items in table 
$sql = "SELECT 
    wp_hud_display.id, 
    wp_hud_display.name, 
    wp_hud_display.resolution, 
    wp_hud_display.user_id, 
    wp_hud_display.instrument_id_1, 
    wp_hud_display.x_loc_1, 
    wp_hud_display.y_loc_1, 
    wp_hud_display.layer_1, 
    wp_hud_display.instrument_id_2, 
    wp_hud_display.x_loc_2, 
    wp_hud_display.y_loc_2, 
    wp_hud_display.layer_2, 
    wp_hud_display.instrument_id_3, 
    wp_hud_display.x_loc_3, 
    wp_hud_display.y_loc_3, 
    wp_hud_display.layer_3, 
    wp_hud_display.instrument_id_4, 
    wp_hud_display.x_loc_4, 
    wp_hud_display.y_loc_4, 
    wp_hud_display.layer_4, 
    wp_hud_instrument.inst_id AS inst1_id, 
    wp_hud_instrument.name AS inst1_name, 
    wp_hud_instrument.image_file AS inst1_image, 
    wp_hud_instrument.font_type AS inst1_ft, 
    wp_hud_instrument.font_size AS inst1_fs, 
    wp_hud_instrument_1.inst_id AS inst2_id, 
    wp_hud_instrument_1.name AS inst2_name, 
    wp_hud_instrument_1.image_file AS inst2_image, 
    wp_hud_instrument_1.font_type AS inst2_ft, 
    wp_hud_instrument_1.font_size AS inst2_fs, 
    wp_hud_instrument_2.inst_id AS inst3_id, 
    wp_hud_instrument_2.name AS inst3_name, 
    wp_hud_instrument_2.image_file AS inst3_image, 
    wp_hud_instrument_2.font_type AS inst3_ft, 
    wp_hud_instrument_2.font_size AS inst3_fs, 
    wp_hud_instrument_3.inst_id AS inst4_id, 
    wp_hud_instrument_3.name AS inst4_name, 
    wp_hud_instrument_3.image_file AS inst4_image, 
    wp_hud_instrument_3.font_type AS inst4_ft, 
    wp_hud_instrument_3.font_size AS inst4_fs 
FROM wp_hud_display 
    LEFT JOIN wp_hud_instrument 
    ON wp_hud_display.instrument_id_1 = wp_hud_instrument.inst_id 
    LEFT JOIN wp_hud_instrument wp_hud_instrument_1 
    ON wp_hud_display.instrument_id_2 = wp_hud_instrument_1.inst_id 
    LEFT JOIN wp_hud_instrument wp_hud_instrument_2 
    ON wp_hud_display.instrument_id_3 = wp_hud_instrument_2.inst_id 
    LEFT JOIN wp_hud_instrument wp_hud_instrument_3 
    ON wp_hud_display.instrument_id_4 = wp_hud_instrument_3.inst_id 
WHERE wp_hud_display.user_id = 1 
GROUP BY wp_hud_display.id"; 

/* create the root element of the xml tree */ 
$xmlRoot = $domtree->createElement("wp_hud_displays"); 
/* append it to the document created */ 
$xmlRoot = $domtree->appendChild($xmlRoot); 

$hud_display_group = $domtree->createElement("hud_display_group"); 
$hud_display_group = $xmlRoot->appendChild($hud_display_group); 

$hud_display = $domtree->createElement("hud_display"); 
$hud_display = $hud_display_group->appendChild($hud_display); 

$instrument_id_1 = $domtree->createElement("instrument_id_1"); 
$instrument_id_1 = $hud_display->appendChild($instrument_id_1); 

$instrument_id_2 = $domtree->createElement("instrument_id_2"); 
$instrument_id_2 = $hud_display->appendChild($instrument_id_2); 

$instrument_id_3 = $domtree->createElement("instrument_id_3"); 
$instrument_id_3 = $hud_display->appendChild($instrument_id_3); 

$instrument_id_4 = $domtree->createElement("instrument_id_4"); 
$instrument_id_4 = $hud_display->appendChild($instrument_id_4); 

    $result = mysql_query($sql); 
    if (!$result) { 
     die('Invalid query: ' . mysql_error()); 
    } 

    if(mysql_num_rows($result)>0) 
    { 
     while($result_array = mysql_fetch_assoc($result)) 
     { 

    /* you should enclose the following two lines in a cicle */ 

$hud_display->appendChild($domtree->createElement('id',$result_array['id'])); 
$hud_display->appendChild($domtree->createElement('name',$result_array['name'])); 
$hud_display->appendChild($domtree->createElement('resolution',$result_array['resolution'])); 
$hud_display->appendChild($domtree->createElement('user_id',$result_array['user_id'])); 

// Instrument 1 
$hud_display->appendChild($domtree->createElement('instrument_id_1',$result_array['instrument_id_1'])); 
$instrument_id_1->appendChild($domtree->createElement('inst_id',$result_array['inst1_id'])); 
$instrument_id_1->appendChild($domtree->createElement('name',$result_array['inst1_name'])); 
$instrument_id_1->appendChild($domtree->createElement('image_name',$result_array['inst1_image'])); 
$instrument_id_1->appendChild($domtree->createElement('font_type',$result_array['inst1_ft'])); 
$instrument_id_1->appendChild($domtree->createElement('font_size',$result_array['inst1_fs'])); 
$hud_display->appendChild($domtree->createElement('x_loc_1',$result_array['x_loc_1'])); 
$hud_display->appendChild($domtree->createElement('y_loc_1',$result_array['y_loc_1'])); 
$hud_display->appendChild($domtree->createElement('layer_1',$result_array['layer_1'])); 

// Instrument 2 
$hud_display->appendChild($domtree->createElement('instrument_id_2',$result_array['instrument_id_2'])); 
$instrument_id_2->appendChild($domtree->createElement('inst_id',$result_array['inst2_id'])); 
$instrument_id_2->appendChild($domtree->createElement('name',$result_array['inst2_name'])); 
$instrument_id_2->appendChild($domtree->createElement('image_name',$result_array['inst2_image'])); 
$instrument_id_2->appendChild($domtree->createElement('font_type',$result_array['inst2_ft'])); 
$instrument_id_2->appendChild($domtree->createElement('font_size',$result_array['inst2_fs'])); 
$hud_display->appendChild($domtree->createElement('x_loc_2',$result_array['x_loc_2'])); 
$hud_display->appendChild($domtree->createElement('y_loc_2',$result_array['y_loc_2'])); 
$hud_display->appendChild($domtree->createElement('layer_2',$result_array['layer_2'])); 

// Instrument 3 
$hud_display->appendChild($domtree->createElement('instrument_id_3',$result_array['instrument_id_3'])); 
    $instrument_id_3->appendChild($domtree->createElement('inst_id',$result_array['inst3_id']));  $instrument_id_3->appendChild($domtree->createElement('name',$result_array['inst3_name'])); 
$instrument_id_3->appendChild($domtree->createElement('image_name',$result_array['inst3_image'])); 
$instrument_id_3->appendChild($domtree->createElement('font_type',$result_array['inst3_ft'])); $instrument_id_3->appendChild($domtree->createElement('font_size',$result_array['inst3_fs'])); 
$hud_display->appendChild($domtree->createElement('x_loc_3',$result_array['x_loc_3'])); 
$hud_display->appendChild($domtree->createElement('y_loc_3',$result_array['y_loc_3'])); 
$hud_display->appendChild($domtree->createElement('layer_3',$result_array['layer_3'])); 



    // Instrument 4 
$hud_display->appendChild($domtree->createElement('instrument_id_4',$result_array['instrument_id_4'])); 
    $instrument_id_4->appendChild($domtree->createElement('inst_id',$result_array['inst4_id'])); 
    $instrument_id_4->appendChild($domtree->createElement('name',$result_array['inst4_name'])); 
    $instrument_id_4->appendChild($domtree->createElement('image_name',$result_array['inst4_image'])); 
    $instrument_id_4->appendChild($domtree->createElement('font_type',$result_array['inst4_ft'])); 
    $instrument_id_4->appendChild($domtree->createElement('font_size',$result_array['inst4_fs'])); $hud_display->appendChild($domtree->createElement('x_loc_4',$result_array['x_loc_4'])); 
    $hud_display->appendChild($domtree->createElement('y_loc_4',$result_array['y_loc_4'])); 
    $hud_display->appendChild($domtree->createElement('layer_4',$result_array['layer_4'])); 

      } 
     } 
    // get the xml printed 

     echo $domtree->saveXML(); 



     //send the xml header to the browser 

    header ("Content-Type:text/xml"); 


     //output the XML data 

    echo $xml; 
    ?> 

Это, как он показывает, когда есть только один набор значений для возврата (wp_hud_display.id)

<wp_hud_displays> 
    <hud_display_group> 
     <hud_display> 
     <instrument_id_1></instrument_id_1> 
     <instrument_id_2></instrument_id_2> 
     <instrument_id_3></instrument_id_3> 
     <instrument_id_4></instrument_id_4> 
     <id>1</id> 
     <name>test display</name> 
     <resolution>1080p</resolution> 
     <user_id>1</user_id> 
     <instrument_id_1>1</instrument_id_1> 
     <x_loc_1>89</x_loc_1> 
     <y_loc_1>79</y_loc_1> 
     <layer_1>1</layer_1> 
     <instrument_id_2>2</instrument_id_2> 
     <x_loc_2>988</x_loc_2> 
     <y_loc_2>98</y_loc_2> 
     <layer_2>1</layer_2> 
     <instrument_id_3>3</instrument_id_3> 
     <x_loc_3>89</x_loc_3> 
     <y_loc_3>90</y_loc_3> 
     <layer_3>1</layer_3> 
     <instrument_id_4>4</instrument_id_4> 
     <x_loc_4>67</x_loc_4> 
     <y_loc_4>76</y_loc_4> 
     <layer_4>1</layer_4> 
     </hud_display> 
    </hud_display_group> 
    </wp_hud_displays> 

Как показывает, когда есть больше чем один wp_hud_display.id WHERE user_id = 1

1test1_gauge001-2_zpsdbe86ca1f.jpg11PID_DISTANCE30100002500101223dfd34412sdf34534056Arail122test1_needle11PID_ENGINE_LOAD211000025200160112025000000002test1_needle11PID_ENGINE_LOAD211000025200160112025000000003new gaugedfsgsdfgfd435430PID_COOLANT_TEMP2434534541023324000000003new gaugedfsgsdfgfd435430PID_COOLANT_TEMP2434534541023324000000004Bla100.jpg2702334395910299000000004Bla100.jpg2702334395910299000000002test1_needle11PID_ENGINE_LOAD211000025200160112025000000001test display1080p118979129889813899014677612dsfdsfsd720p12321342323213224232123143423444342 

то, что я после того, как он не выглядеть, как правильный вывод XML (как в первом примере), независимо от того, сколько наборов записей возвращаются.

+0

Почему бы и нет. Попробуйте сделать это – RiggsFolly

+0

Вы можете сделать это, используя цикл for: for ($ i = 0; $ i user1977204

+0

Дополнительная информация добавлена ​​в вопрос – Dan

ответ

0

Если вы хотите, чтобы узел hud_display повторялся, включите внутри while, для каждой итерации будет создан новый hud_display. Что-то вроде этого должно работать:

// create a dom document with encoding utf8 
    $domtree = new DOMDocument('1.0', 'UTF-8'); 

    //database configuration and extract your data 

    /* create the root element of the xml tree */ 
    $xmlRoot = $domtree->createElement("wp_hud_displays"); 
    /* append it to the document created */ 
    $xmlRoot = $domtree->appendChild($xmlRoot); 

    $hud_display_group = $domtree->createElement("hud_display_group"); 
    $hud_display_group = $xmlRoot->appendChild($hud_display_group); 

    $result = mysql_query($sql); 
    if (!$result) { 
     die('Invalid query: ' . mysql_error()); 
    } 

    if(mysql_num_rows($result)>0) 
    { 
     while($result_array = mysql_fetch_assoc($result)) 
     { 
      $hud_display = $domtree->createElement("hud_display"); 
      $hud_display = $hud_display_group->appendChild($hud_display); 

      $instrument_id_1 = $domtree->createElement("instrument_id_1"); 
      $instrument_id_1 = $hud_display->appendChild($instrument_id_1); 

      $instrument_id_2 = $domtree->createElement("instrument_id_2"); 
      $instrument_id_2 = $hud_display->appendChild($instrument_id_2); 

      $instrument_id_3 = $domtree->createElement("instrument_id_3"); 
      $instrument_id_3 = $hud_display->appendChild($instrument_id_3); 

      $instrument_id_4 = $domtree->createElement("instrument_id_4"); 
      $instrument_id_4 = $hud_display->appendChild($instrument_id_4); 

      /* you should enclose the following two lines in a cicle */ 

      $hud_display->appendChild($domtree->createElement('id',$result_array['id'])); 
      $hud_display->appendChild($domtree->createElement('name',$result_array['name'])); 
      $hud_display->appendChild($domtree->createElement('resolution',$result_array['resolution'])); 
      $hud_display->appendChild($domtree->createElement('user_id',$result_array['user_id'])); 

      // Instrument 1 
      $hud_display->appendChild($domtree->createElement('instrument_id_1',$result_array['instrument_id_1'])); 
      $instrument_id_1->appendChild($domtree->createElement('inst_id',$result_array['inst1_id'])); 
      $instrument_id_1->appendChild($domtree->createElement('name',$result_array['inst1_name'])); 
      $instrument_id_1->appendChild($domtree->createElement('image_name',$result_array['inst1_image'])); 
      $instrument_id_1->appendChild($domtree->createElement('font_type',$result_array['inst1_ft'])); 
      $instrument_id_1->appendChild($domtree->createElement('font_size',$result_array['inst1_fs'])); 
      $hud_display->appendChild($domtree->createElement('x_loc_1',$result_array['x_loc_1'])); 
      $hud_display->appendChild($domtree->createElement('y_loc_1',$result_array['y_loc_1'])); 
      $hud_display->appendChild($domtree->createElement('layer_1',$result_array['layer_1'])); 

      // Instrument 2 
      $hud_display->appendChild($domtree->createElement('instrument_id_2',$result_array['instrument_id_2'])); 
      $instrument_id_2->appendChild($domtree->createElement('inst_id',$result_array['inst2_id'])); 
      $instrument_id_2->appendChild($domtree->createElement('name',$result_array['inst2_name'])); 
      $instrument_id_2->appendChild($domtree->createElement('image_name',$result_array['inst2_image'])); 
      $instrument_id_2->appendChild($domtree->createElement('font_type',$result_array['inst2_ft'])); 
      $instrument_id_2->appendChild($domtree->createElement('font_size',$result_array['inst2_fs'])); 
      $hud_display->appendChild($domtree->createElement('x_loc_2',$result_array['x_loc_2'])); 
      $hud_display->appendChild($domtree->createElement('y_loc_2',$result_array['y_loc_2'])); 
      $hud_display->appendChild($domtree->createElement('layer_2',$result_array['layer_2'])); 

      // Instrument 3 
      $hud_display->appendChild($domtree->createElement('instrument_id_3',$result_array['instrument_id_3'])); 
      $instrument_id_3->appendChild($domtree->createElement('inst_id',$result_array['inst3_id']));  
      $instrument_id_3->appendChild($domtree->createElement('name',$result_array['inst3_name'])); 
      $instrument_id_3->appendChild($domtree->createElement('image_name',$result_array['inst3_image'])); 
      $instrument_id_3->appendChild($domtree->createElement('font_type',$result_array['inst3_ft'])); 
      $instrument_id_3->appendChild($domtree->createElement('font_size',$result_array['inst3_fs'])); 
      $hud_display->appendChild($domtree->createElement('x_loc_3',$result_array['x_loc_3'])); 
      $hud_display->appendChild($domtree->createElement('y_loc_3',$result_array['y_loc_3'])); 
      $hud_display->appendChild($domtree->createElement('layer_3',$result_array['layer_3'])); 

      // Instrument 4 
      $hud_display->appendChild($domtree->createElement('instrument_id_4',$result_array['instrument_id_4'])); 
      $instrument_id_4->appendChild($domtree->createElement('inst_id',$result_array['inst4_id'])); 
      $instrument_id_4->appendChild($domtree->createElement('name',$result_array['inst4_name'])); 
      $instrument_id_4->appendChild($domtree->createElement('image_name',$result_array['inst4_image'])); 
      $instrument_id_4->appendChild($domtree->createElement('font_type',$result_array['inst4_ft'])); 
      $instrument_id_4->appendChild($domtree->createElement('font_size',$result_array['inst4_fs'])); 
      $hud_display->appendChild($domtree->createElement('x_loc_4',$result_array['x_loc_4'])); 
      $hud_display->appendChild($domtree->createElement('y_loc_4',$result_array['y_loc_4'])); 
      $hud_display->appendChild($domtree->createElement('layer_4',$result_array['layer_4'])); 

     } 
    } 
// get the xml printed 
echo $domtree->saveXML(); 

//send the xml header to the browser 
header ("Content-Type:text/xml"); 

//output the XML data 
echo $xml; 
+0

Спасибо user1977204, я пробовал ваши перегрузки для включения узлов HUD внутри цикла, но он остается прежним, возвращает один набор «wp_hud_display.id», работает отлично, но при этом отбрасывает форматирование XML при возврате большего, чем один комплект. Я также попытался добавить «for ($ i = 0; $ i Dan

+0

У вас есть ошибка, когда из базы данных выдается несколько наборов? Проверьте журналы, но если эхо всегда печатает один набор запросов mysql, то, возможно, есть только одна строка, отлаживайте свой запрос для проверки того, что выбрано более одной строки. Также последняя строка echo $ xml; ничего не делает, переменная $ xml никогда не используется. – user1977204

+0

В базе данных есть два набора: «WHERE wp_hud_display.user_id = 1» в запросе SQL, выбирая необходимые наборы, я меняю его в базе данных, чтобы он возвращал два набора, то есть когда он отбрасывает форматирование. и выводит результат с помощью BOTH наборов результатов, отображаемых на странице. Затем я меняю user_id на один из наборов на другое значение и отлично работает, отображая результат в форматировании XML. – Dan