За последние 24 часа нас посетили 52394 программиста и 1757 роботов. Сейчас ищут 939 программистов ...

Как правильно парсить и затем выводить данные ?

Тема в разделе "PHP для новичков", создана пользователем Sice, 20 май 2015.

  1. Sice

    Sice Активный пользователь

    С нами с:
    16 фев 2012
    Сообщения:
    45
    Симпатии:
    0
    Добрый день, друзья. Подскажите пожалуйста как правильнее парсить данные и как организовать цикл для вывода данных парсинга.
    Я обращаюсь на сайт, мне приходит ответ такого рода, если парсить в XML:
    Код (Text):
    1.  
    2. <result>
    3. <status>1</status>
    4. <num_results>100</num_results>
    5. <total_results>500</total_results>
    6. <results_remaining>400</results_remaining>
    7. <matches>
    8. <match>
    9. <match_id>1487575980</match_id>
    10. <match_seq_num>1334122787</match_seq_num>
    11. <start_time>1432118783</start_time>
    12. <lobby_type>7</lobby_type>
    13. <radiant_team_id>0</radiant_team_id>
    14. <dire_team_id>0</dire_team_id>
    15. <players>
    16. <player>
    17. <account_id>4294967295</account_id>
    18. <player_slot>0</player_slot>
    19. <hero_id>26</hero_id>
    20. </player>
    21. <player>
    22. <account_id>22032060</account_id>
    23. <player_slot>1</player_slot>
    24. <hero_id>22</hero_id>
    25. </player>
    26. <player>
    27. <account_id>24802150</account_id>
    28. <player_slot>2</player_slot>
    29. <hero_id>8</hero_id>
    30. </player>
    31. <player>
    32. <account_id>4294967295</account_id>
    33. <player_slot>3</player_slot>
    34. <hero_id>23</hero_id>
    35. </player>
    36. <player>
    37. <account_id>4294967295</account_id>
    38. <player_slot>4</player_slot>
    39. <hero_id>35</hero_id>
    40. </player>
    41. <player>
    42. <account_id>4294967295</account_id>
    43. <player_slot>128</player_slot>
    44. <hero_id>25</hero_id>
    45. </player>
    46. <player>
    47. <account_id>4294967295</account_id>
    48. <player_slot>129</player_slot>
    49. <hero_id>73</hero_id>
    50. </player>
    51. <player>
    52. <account_id>4294967295</account_id>
    53. <player_slot>130</player_slot>
    54. <hero_id>19</hero_id>
    55. </player>
    56. <player>
    57. <account_id>4294967295</account_id>
    58. <player_slot>131</player_slot>
    59. <hero_id>88</hero_id>
    60. </player>
    61. <player>
    62. <account_id>138657453</account_id>
    63. <player_slot>132</player_slot>
    64. <hero_id>46</hero_id>
    65. </player>
    66. </players>
    67. </match>
    68. <match>
    69. <match_id>1486500565</match_id>
    70. <match_seq_num>1333203789</match_seq_num>
    71. <start_time>1432069365</start_time>
    72. <lobby_type>7</lobby_type>
    73. <radiant_team_id>0</radiant_team_id>
    74. <dire_team_id>0</dire_team_id>
    75. <players>
    76. <player>
    77. <account_id>4294967295</account_id>
    78. <player_slot>0</player_slot>
    79. <hero_id>84</hero_id>
    80. </player>
    81. <player>
    82. <account_id>4294967295</account_id>
    83. <player_slot>1</player_slot>
    84. <hero_id>29</hero_id>
    85. </player>
    86. <player>
    87. <account_id>4294967295</account_id>
    88. <player_slot>2</player_slot>
    89. <hero_id>93</hero_id>
    90. </player>
    91. <player>
    92. <account_id>97739429</account_id>
    93. <player_slot>3</player_slot>
    94. <hero_id>12</hero_id>
    95. </player>
    96. <player>
    97. <account_id>157387016</account_id>
    98. <player_slot>4</player_slot>
    99. <hero_id>76</hero_id>
    100. </player>
    101. <player>
    102. <account_id>81863485</account_id>
    103. <player_slot>128</player_slot>
    104. <hero_id>33</hero_id>
    105. </player>
    106. <player>
    107. <account_id>48311512</account_id>
    108. <player_slot>129</player_slot>
    109. <hero_id>37</hero_id>
    110. </player>
    111. <player>
    112. <account_id>67701328</account_id>
    113. <player_slot>130</player_slot>
    114. <hero_id>2</hero_id>
    115. </player>
    116. <player>
    117. <account_id>22032060</account_id>
    118. <player_slot>131</player_slot>
    119. <hero_id>22</hero_id>
    120. </player>
    121. <player>
    122. <account_id>24802150</account_id>
    123. <player_slot>132</player_slot>
    124. <hero_id>8</hero_id>
    125. </player>
    126. </players>
    127. </match>
    128. <match>
    129. <match_id>1485822121</match_id>
    130. <match_seq_num>1332607189</match_seq_num>
    131. <start_time>1432046719</start_time>
    132. <lobby_type>7</lobby_type>
    133. <radiant_team_id>0</radiant_team_id>
    134. <dire_team_id>0</dire_team_id>
    135. <players>
    136. <player>
    137. <account_id>4294967295</account_id>
    138. <player_slot>0</player_slot>
    139. <hero_id>71</hero_id>
    140. </player>
    141. <player>
    142. <account_id>4294967295</account_id>
    143. <player_slot>1</player_slot>
    144. <hero_id>67</hero_id>
    145. </player>
    146. <player>
    147. <account_id>103810932</account_id>
    148. <player_slot>2</player_slot>
    149. <hero_id>79</hero_id>
    150. </player>
    151. <player>
    152. <account_id>4294967295</account_id>
    153. <player_slot>3</player_slot>
    154. <hero_id>106</hero_id>
    155. </player>
    156. <player>
    157. <account_id>4294967295</account_id>
    158. <player_slot>4</player_slot>
    159. <hero_id>74</hero_id>
    160. </player>
    161. <player>
    162. <account_id>22032060</account_id>
    163. <player_slot>128</player_slot>
    164. <hero_id>22</hero_id>
    165. </player>
    166. <player>
    167. <account_id>24802150</account_id>
    168. <player_slot>129</player_slot>
    169. <hero_id>5</hero_id>
    170. </player>
    171. <player>
    172. <account_id>128966659</account_id>
    173. <player_slot>130</player_slot>
    174. <hero_id>44</hero_id>
    175. </player>
    176. <player>
    177. <account_id>4294967295</account_id>
    178. <player_slot>131</player_slot>
    179. <hero_id>7</hero_id>
    180. </player>
    181. <player>
    182. <account_id>4294967295</account_id>
    183. <player_slot>132</player_slot>
    184. <hero_id>61</hero_id>
    185. </player>
    186. </players>
    187. </match>
    188. </matches>
    И так далее, таких <match> много. Подскажите как это правильно обработать ? Вывести в итоге каждый матч (<match>) в отдельной строке.

    И второй вопрос, как можно "заходить" во внутрь каждого матча (<match>) и вытаскивать данные оттуда в одном файле?
    Чтобы в одном файле я отображал список этих самых матчей и некоторую индивидуальную информацию уже конкретно по каждому матчу ?


    Вот ответ сервера, если парсить через JSON
    Код (Text):
    1.  
    2. {
    3.     "result": {
    4.         "status": 1,
    5.         "num_results": 100,
    6.         "total_results": 500,
    7.         "results_remaining": 400,
    8.         "matches": [
    9.             {
    10.                 "match_id": 1487575980,
    11.                 "match_seq_num": 1334122787,
    12.                 "start_time": 1432118783,
    13.                 "lobby_type": 7,
    14.                 "radiant_team_id": 0,
    15.                 "dire_team_id": 0,
    16.                 "players": [
    17.                     {
    18.                         "account_id": 4294967295,
    19.                         "player_slot": 0,
    20.                         "hero_id": 26
    21.                     },
    22.                     {
    23.                         "account_id": 22032060,
    24.                         "player_slot": 1,
    25.                         "hero_id": 22
    26.                     },
    27.                     {
    28.                         "account_id": 24802150,
    29.                         "player_slot": 2,
    30.                         "hero_id": 8
    31.                     },
    32.                     {
    33.                         "account_id": 4294967295,
    34.                         "player_slot": 3,
    35.                         "hero_id": 23
    36.                     },
    37.                     {
    38.                         "account_id": 4294967295,
    39.                         "player_slot": 4,
    40.                         "hero_id": 35
    41.                     },
    42.                     {
    43.                         "account_id": 4294967295,
    44.                         "player_slot": 128,
    45.                         "hero_id": 25
    46.                     },
    47.                     {
    48.                         "account_id": 4294967295,
    49.                         "player_slot": 129,
    50.                         "hero_id": 73
    51.                     },
    52.                     {
    53.                         "account_id": 4294967295,
    54.                         "player_slot": 130,
    55.                         "hero_id": 19
    56.                     },
    57.                     {
    58.                         "account_id": 4294967295,
    59.                         "player_slot": 131,
    60.                         "hero_id": 88
    61.                     },
    62.                     {
    63.                         "account_id": 138657453,
    64.                         "player_slot": 132,
    65.                         "hero_id": 46
    66.                     }
    67.                 ]
    68.                
    69.             },
    70.             {
    71.                 "match_id": 1486500565,
    72.                 "match_seq_num": 1333203789,
    73.                 "start_time": 1432069365,
    74.                 "lobby_type": 7,
    75.                 "radiant_team_id": 0,
    76.                 "dire_team_id": 0,
    77.                 "players": [
    78.                     {
    79.                         "account_id": 4294967295,
    80.                         "player_slot": 0,
    81.                         "hero_id": 84
    82.                     },
    83.                     {
    84.                         "account_id": 4294967295,
    85.                         "player_slot": 1,
    86.                         "hero_id": 29
    87.                     },
    88.                     {
    89.                         "account_id": 4294967295,
    90.                         "player_slot": 2,
    91.                         "hero_id": 93
    92.                     },
    93.                     {
    94.                         "account_id": 97739429,
    95.                         "player_slot": 3,
    96.                         "hero_id": 12
    97.                     },
    98.                     {
    99.                         "account_id": 157387016,
    100.                         "player_slot": 4,
    101.                         "hero_id": 76
    102.                     },
    103.                     {
    104.                         "account_id": 81863485,
    105.                         "player_slot": 128,
    106.                         "hero_id": 33
    107.                     },
    108.                     {
    109.                         "account_id": 48311512,
    110.                         "player_slot": 129,
    111.                         "hero_id": 37
    112.                     },
    113.                     {
    114.                         "account_id": 67701328,
    115.                         "player_slot": 130,
    116.                         "hero_id": 2
    117.                     },
    118.                     {
    119.                         "account_id": 22032060,
    120.                         "player_slot": 131,
    121.                         "hero_id": 22
    122.                     },
    123.                     {
    124.                         "account_id": 24802150,
    125.                         "player_slot": 132,
    126.                         "hero_id": 8
    127.                     }
    128.                 ]
    129.                
    130.             },
    Как будет правильнее и удобнее парсить ?

    Заранее большое спасибо Вам за ответы!
     
  2. p@R@dox 55RU

    p@R@dox 55RU Зэк
    [ БАН ]

    С нами с:
    21 май 2014
    Сообщения:
    1.358
    Симпатии:
    7
    Адрес:
    с планеты Ялмез
    проще с json и быстрее, а вложенность парсить можно рекурсивно :)
     
  3. Sice

    Sice Активный пользователь

    С нами с:
    16 фев 2012
    Сообщения:
    45
    Симпатии:
    0
    покажите пожалуйста пример, я только изучаю php
     
  4. p@R@dox 55RU

    p@R@dox 55RU Зэк
    [ БАН ]

    С нами с:
    21 май 2014
    Сообщения:
    1.358
    Симпатии:
    7
    Адрес:
    с планеты Ялмез
    ..... в начале надо пропустить json-ответ через jsone_decode, а потом уже "выгребать" всё...
    всё просто ;)
     
  5. Sice

    Sice Активный пользователь

    С нами с:
    16 фев 2012
    Сообщения:
    45
    Симпатии:
    0
    я понимаю, что за меня делать никто не будет, но ведь это не пример) вы говорите сейчас на не понятном для меня языке

    Тащу данные я таким образом:
    Код (PHP):
    1. $url = file_get_contents("http://site.com); 
    2. $content = json_decode($url, true);
    В массиве $content хранится весь ответа от сервера. А как его мне красиво в читабельный для пользователя вид привести ?
     
  6. p@R@dox 55RU

    p@R@dox 55RU Зэк
    [ БАН ]

    С нами с:
    21 май 2014
    Сообщения:
    1.358
    Симпатии:
    7
    Адрес:
    с планеты Ялмез
    раз вложенность не может быть разная то - рекурсивно...
    соответственно, нужно сделать разбор этого "$content" внутри функции и плюс оборачивать html тегами для красоты :)

    пример рекурсии
    Код (Text):
    1. function recursion($a)
    2. {
    3.     if ($a < 20) {
    4.         echo "$a\n";
    5.         recursion($a + 1);
    6.     }
    7. }
    8. ?>
     
  7. Sice

    Sice Активный пользователь

    С нами с:
    16 фев 2012
    Сообщения:
    45
    Симпатии:
    0
    Спасибо, подскажите пожалуйста, как правильно цикл (вывод всех данных) по массиву соорудить ?
    Массив многомерный, такой код у меня не работает:
    Код (PHP):
    1. $url_history = file_get_contents("https://site.com"); 
    2. $match_history = json_decode($url_history, true);
    3.  
    4. foreach ($match_history as  &$mh) {
    5.     echo $mh[]; 
    6. }
    7.  
     
  8. p@R@dox 55RU

    p@R@dox 55RU Зэк
    [ БАН ]

    С нами с:
    21 май 2014
    Сообщения:
    1.358
    Симпатии:
    7
    Адрес:
    с планеты Ялмез
    если чисто для проверки объекта, то будет выглядеть так
    Код (Text):
    1. foreach ($match_history as  $mh) {
    2. echo '=======================<pre>';
    3.   print_r( $mh );
    4.   echo '</pre>-------------------------------';
    5. }
     
  9. Sice

    Sice Активный пользователь

    С нами с:
    16 фев 2012
    Сообщения:
    45
    Симпатии:
    0
    Спасибо большое Вам за помощь! Буду дальше разбираться.