reading xml - solved


Let’s say I have the following xml file

  <district id="1">
     <detector name="dt1" id="20" type="up" />
     <detector name="dt2" id="22" type="up" />
     <detector name="dt1" id="25" type="up" />

and I am accessing the detectors with name=“dt1” as follows

$dom = new DomDocument();

$xp = new domxpath($dom);

$data = $xp->query("//detector[@name='dt1']");

How do I access the various attributes in the nodes that I have selected? For example, how could I print out the name, id and type for each detector named dt1?

Okay, so I eventually found that this is an easy problem to solve if using simplexml:

$s = simplexml_load_file('test.xml');
foreach($s->xpath("//detector[@name='dt1']") as $data){
  $atts = $data->attributes();
  echo $atts['name']." ".$atts['id']." ".$atts['type']."<br>";

I am still curious to know how to access the attributes from the Dom method. Im sure it’s pretty similar…

DomElement->getAttribute() perhaps? I have never used XML parsing in PHP before though, so shoot me if I’m mistaken here.

On a sidenote: please realize that using a DOM parser for XML is not ‘using the right tool for the right job’, but then again, there are a lot of ways to get the job done :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service