I have an XML file, how can I parse it using PHP? Note that the parameter has both a value and an attribute.

<?xml version="1.0" encoding="UTF-8"?> <xml> <price currency="EUR"></price> <phone currency="4.95" >val 1</phone> <phone currency="5.95" >val 2</phone> </xml> 

  • Carefully. The parameter contains both attribute and value. Therefore, it does not parse. - Pavel Zhukovsky
  • Or maybe just inattentively reading manuals? simplexml_load_string($str)->price->attributes()->currency - DaemonHK
  • And for phone make an example? How to get both value and attribute? - Pavel Zhukovsky
  • You bother to read the help then, the values ​​through the $obj->field attributes through $obj['attr'] - teran

1 answer 1

So, what was able to remember)

 $str="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <xml> <price currency=\"EUR\"></price> <phone currency=\"4.95\" >val 1</phone> <phone currency=\"5.95\" >val 2</phone> </xml>"; $xml=simplexml_load_string($str); echo $xml->price->attributes()->currency; //читаем атрибут foreach($xml->phone as $phone){ echo $phone->attributes()->currency; //читаем атрибут echo (string)$phone->{0}; //читаем значение, где {0} - указатель на "первый" элемент unset($phone); } 
  • do not complicate, (float) $phone['currency'] - teran
  • @teran That's all right to say everything - Dmitriy
  • @teran is usually read in the stream, where the text is also floating point, so it remains in memory)) - DaemonHK
  • @DaemonHK I mean that access to an attribute through square brackets by name (well, or xs what’s the floating point you mentioned) - teran
  • @teran thought you were talking about {0} )) and about your refinement - the habit of working with objects, and besides, a node can have several attributes that are sometimes easier to process with a cycle - DaemonHK