PHP解析XML数据

时间:2014-03-21 22:35:06

标签: php xml parsing

我有这样的事情:

  <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>

现在,我需要将这些数据解析为PHP变量,如下所示:

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

......等等,有没有办法做到这一点?

尝试过bash,但如果能用php完成它会更容易

4 个答案:

答案 0 :(得分:4)

PHP支持XML。我喜欢使用SimpleXML

$xml = new SimpleXMLElement($xmlString);

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

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

易。

DEMO:https://eval.in/124545

答案 1 :(得分:0)

您可以使用xml Parser尝试: http://de1.php.net/xmlBest XML Parser for PHP

答案 2 :(得分:0)

simplexml_load_file()simplexml_load_string()将xml作为对象加载。

答案 3 :(得分:0)

如果需要从XML获取数据,请使用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)');

演示:https://eval.in/124553