Hello. I tried to figure it out myself, but it doesn’t work for me.

In general, the following case. From another server in response to my requests comes XML - PASTEBIN

I <achiev id = 1>INT</achiev> trying to access the <achiev id = 1>INT</achiev> elements and the elements of the <playerTalents> block.

Tried through SimpleXML, strictly acting documentation:

 <?php $xml = file_get_contents($url); $stat = new SimpleXMLElement($xml); foreach ($stat->data->user->id as $id { switch((string) $achieve['id']) { // Получение атрибутов элемента по индексу case '1': $dmg = $id; break; } } ?> 

But something nonsense turns out, constantly returns 0.

So, the question is, how can I still get to the element I need?

  • Give an example of the file to be received and what should get from it then on the PHP side - chernomyrdin
  • @chernomyrdin - I gave a link to the sample XML I received. Yes, and what you need and from what elements to get, also indicated. - Vitaliy RS

1 answer 1

I offer this option (data conversion into an array):

 function objectsIntoArray($arrObjData, $arrSkipIndices = array()) { $arrData = array(); // if input is object, convert into array if (is_object($arrObjData)) { $arrObjData = get_object_vars($arrObjData); } if (is_array($arrObjData)) { foreach ($arrObjData as $index => $value) { if (is_object($value) || is_array($value)) { $value = objectsIntoArray($value, $arrSkipIndices); // recursive call } if (in_array($index, $arrSkipIndices)) { continue; } $arrData[$index] = $value; } } return $arrData; } $xmlStr = file_get_contents($xmlUrl); //получили данные $xmlObj = simplexml_load_string($xmlStr); //распарсили $arrXml = objectsIntoArray($xmlObj); //преобразовали в массив $arrXml['data']['user']['collections'][0] - доступ к данным. 

Generally, if it is not clear how the data is currently stored, output it using print_r() or var_dump() . This will provide an opportunity to see which indices the particular array is currently using, and how best to display it.

  • @Magos thanks for the detailed answer. The problem is that it constantly returns a bunch of NULL, no matter how I rule the document structure. Now I will try your option. - Vitaliy RS
  • @Magos returns Null. - Vitaliy RS
  • I studied the conclusion myself and in detail. Try the test: `// Achivki here: $ arrXml ['playerAchievements'] ['achiev'] echo" <pre> "; print_r ($ arrXml ['playerAchievements'] ['achiev']); echo "</ pre>"; ` - Magos
  • In order to understand the structure, output echo "<pre>"; print_r ($ arrXml); echo "</ pre>"; Indenting everything will be visible. - Magos
  • @Magos already figured out, thanks. Just missed, checked with different XML and in some the necessary values ​​were equal to 0 - Vitaliy RS