K
K
Kirill Sirenko2013-02-15 09:00:09
PHP
Kirill Sirenko, 2013-02-15 09:00:09

Parsing XML from the ISPManager API

Good afternoon!
There was a need to parse the xml that is returned from the ispamanger api.
Actually, the specifics: I request a list of users, everyone has a set of parameters framed by paired tags, but there is a <disabled /> parameter that is single and available to those users who are disabled.
I can't parse it at all. There is a code that finds these tags, but what to do next, because this tag has no pair and no value (what is inside the node), how then to determine whether the user is disabled or not?

I have a standard parameter search structure like this:

  if( $doc = domxml_open_mem( $result ) ){
    $root = $doc->document_element();
    $ar = array();
$name_array = $root->get_elements_by_tagname('name');
    $i = 0;
    foreach ($name_array as $name) 
    {
      $ar[$i]['name'] .= $name->get_content();
      $i++;
    }


What to do with this single tag?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
PomanoB, 2013-02-15
@Chieftec

In short, you need to look for elem tags, not name tags, and move on from them.

<?php
header('Content-type: text/plain;');
$xml = '
<doc>
  <elem>
    <name>belykrolik</name>
    <owner color="blue">golov</owner>
    <disk used="124" limit="1024"/>
    <bandwidth used="24" limit="100000000"/>
    <disabled/>
    <preset>test</preset>
    <note>01/02/2014</note>
  </elem>

  <elem>
    <name>belykrolik2</name>
    <owner color="blue">golov</owner>
    <disk used="124" limit="1024"/>
    <bandwidth used="24" limit="100000000"/>
    <preset>test</preset>
    <note>01/02/2014</note>
  </elem>
</doc>';

$ar = array();
$i = 0;
$x = simplexml_load_string($xml);
foreach($x->elem as $elem)
{
  $ar[$i]['name'] = (string)$elem->name;
  $ar[$i]['disabled'] = (bool)$elem->disabled;
  
  $i++;
}
var_dump($ar);

Result:
array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(10) "belykrolik"
    ["disabled"]=>
    bool(true)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(11) "belykrolik2"
    ["disabled"]=>
    bool(false)
  }
}

W
WEBIVAN, 2013-02-15
@WEBIVAN

Why get and parse XML at all?
Add the out=json parameter and decode via json_decode, it will be faster and less resource intensive.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question