简体   繁体   中英

Extract from XML in PHP

<toplevel>
 <CompleteSuggestion>
  <suggestion data="shook ones part 2"/>
 </CompleteSuggestion>
 <CompleteSuggestion>
  <suggestion data="shook me all night long"/>
 </CompleteSuggestion>
 <CompleteSuggestion>
  <suggestion data="shook ones instrumental"/>
 </CompleteSuggestion>
 <CompleteSuggestion>
  <suggestion data="shook me all night long lyrics"/>
 </CompleteSuggestion>
</toplevel>

I want to extract "shook ones part 2" from this XML output. I have gone through every solution, but I'm unable to do this. I tried this:

<?php
$url = 'http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=shook&ds=yt';
$exact = simplexml_load_file($url);
echo $exact->CompleteSuggestion[0]->suggestion;
?>

shook ones part 2 is value of an attribute data of suggestion . So you should get all attributes of a suggestion with function attributes() and select data :

$exact = simplexml_load_file('$url');
echo $exact->CompleteSuggestion[0]->suggestion->attributes()->data;

Omit the single quotes in

simplexml_load_file('$url');
                    ^    ^

You can use DOMDocumen t for this. The below example will search the tag suggestion and echo the data attribute:

$domDocument = new DOMDocument();
$domDocument->loadXML( $xml );

$value = $domDocument->getElementsByTagName( "suggestion" );
foreach ( $value as $e ) {
    echo $e->getAttribute( "data" )."<br>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM