0

I want to read attribute values of XML tags from Google Suggestions XML. Technologies I use are PHP and SimpleXML. I also can use JavaScript. Here is the Google Suggestions XML http://clients1.google.com/complete/search?hl=en&output=toolbar&q=computer or http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=Computer

The format of XML file:

<toplevel>
  <CompleteSuggestion>
  <suggestion data="computershare"/>
  </CompleteSuggestion>
  <CompleteSuggestion>
  <suggestion data="computer desk"/>
  </CompleteSuggestion>
  <CompleteSuggestion>
  <suggestion data="computer science"/>
  </CompleteSuggestion>
</toplevel>

I'm using this code to read XML file:

<?php
$xml=simplexml_load_file("http://clients1.google.com/complete/search?hl=en&output=toolbar&q=computer");
echo $xml->getName() . "<br>";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br>";
  } 
?>

Output:

toplevel
CompleteSuggestion:
CompleteSuggestion:
CompleteSuggestion:
CompleteSuggestion:
CompleteSuggestion:
CompleteSuggestion:

I've never worked with XML files, therefore don't know how to read the ATTRIBUTES values of XML tags. i.e.
computershare
computer desk
computer science
etc, in the above XML file.

Please help me.


The Question that duplicates to my question is not answering what I want to ask and didn't help me to solve my problem. Therefore posted question.

Mohsin
  • 31
  • 5
  • 1
    Quote (http://www.php.net/manual/en/simplexml.examples-basic.php): `Access attributes of an element just as you would elements of an array.` – hindmost Mar 04 '14 at 07:15
  • This question is not a duplicate of http://stackoverflow.com/questions/4625045/how-to-access-element-attributes-with-simplexml but of http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml - which the first one actually points to as duplicate ;--) – Jan Doggen Mar 06 '14 at 08:54

2 Answers2

1

this should work:

foreach($xml->children() as $child)
{
    foreach($child->suggestion[0]->attributes() as $data);
    echo $child->getName() . ": " . $data . "<br>";
}
Kiko
  • 818
  • 8
  • 13
0

Quote:

Access attributes of an element just as you would elements of an array.

foreach($xml->children() as $child){
    echo $child->getName() . ": " . $child . ($child['data']? " | data: " . $child['data'] : "") . "<br>";
}
hindmost
  • 7,125
  • 3
  • 27
  • 39