0

I have something like this:

  <client type="s" name="root" desc="" protocol="server" protocolext="" au="0" thid="0x15e9190">
     <request="0000" srvid="0000" time="" history="" answered=""></request>
     <times login="2013-04-16T10:59:16+0200" online="7001" idle="0"></times>
     <connection ip="127.0.0.1" port="0">OK</connection>
  </client>

Now, i need to parse this data into a PHP variables, something like this:

 $client_type = s; $name = root; $conn_ip = 127.0.0.1;

...and so on,is there a way to do that?

Tried bash, but it would be much easier if it can be done with php

skymario84
  • 123
  • 1
  • 12

4 Answers4

4

PHP has XML support. I like to use SimpleXML.

$xml = new SimpleXMLElement($xmlString);

$client_type = (string)$xml['type'];
$name = (string)$xml['name'];

$conn_ip = (string)$xml->connection['ip'];

Easy.

DEMO: https://eval.in/124545

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Thanks for this, will test it tomorrow, a newb question: Why is there (string) in front of an $xml? And how would i extract "OK" this way? – skymario84 Mar 21 '14 at 22:52
  • 1
    1. Things like `$xml['name']` are `SimpleXMLElement` *objects*, [casting to a string](http://www.php.net/manual/en/language.types.type-juggling.php) in this way gets their text value (`"root"`). 2. `(string) $xml->connection`. See also, http://php.net/simplexml.examples-basic – salathe Mar 21 '14 at 23:09
  • This works great, but when i download xml file i have multiple structures as the above one, how can i do it with multiple structures? – skymario84 Mar 22 '14 at 07:44
  • You'd have to make sure all the `` tags are under a root element. Then `$root->client` would be an array of elements. Loop over `$root->client` and get the info for each item. – gen_Eric Mar 22 '14 at 19:16
0

You can try it with a xml Parser: http://de1.php.net/xml, Best XML Parser for PHP

Community
  • 1
  • 1
Hoff
  • 243
  • 1
  • 6
  • thanks for that, i know how to use xmlparser on a normal xml syntax Mario but i don't know how to do that with a value inside a tag, can you give me an example? Thanks in advance – skymario84 Mar 21 '14 at 22:43
0

simplexml_load_file() or simplexml_load_string() loads xml as an object.

Max
  • 765
  • 5
  • 12
0

If you need to fetch data from a XML use Xpath:

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$client_type = $xpath->evaluate('string(/client/@type)'); 
$name = $xpath->evaluate('string(/client/@name)');; 
$conn_ip = $xpath->evaluate('string(/client/connection/@ip)');

Demo: https://eval.in/124553

ThW
  • 19,120
  • 3
  • 22
  • 44