Getting XML attributes in PHP

Looked at a few other SO posts on this but no joy.

I've got this code:

$url = "http://itunes.apple.com/us/rss/toppaidapplications/limit=10/genre=6014/xml";
$string = file_get_contents($url);
$string = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $string);
$xml = simplexml_load_string($string);

foreach ($xml->entry as $val) {
    echo "RESULTS: " . $val->attributes() . "\n";

but I can't get any results. I'm specifically interested in getting the ID value which would be 549592189 in this fragment:

<id im:id="549592189" im:bundleId="com.activision.wipeout">http://itunes.apple.com/us/app/wipeout/id549592189?mt=8&amp;uo=2</id>

Any suggestions?

Answers


SimpleXML gives you can easy way to drill down in the XML structure and get the element(s) you want. No need for the regex, whatever it does.

<?php

// Load XML
$url = "http://itunes.apple.com/us/rss/toppaidapplications/limit=10/genre=6014/xml";
$string = file_get_contents($url);
$xml = new SimpleXMLElement($string);

// Get the entries
$entries = $xml->entry;

foreach($entries as $e){
    // Get each entriy's id
    $id = $e->id;
    // Get the attributes
    // ID is in the "im" namespace
    $attr = $id->attributes('im', TRUE);
    // echo id
    echo $attr['id'].'<br/>';
}

DEMO: http://codepad.viper-7.com/qNo7gs


Try with xpath:

$doc     = new DOMDocument;
@$doc->loadHTML($string);
$xpath   = new DOMXpath($doc);
$r       = $xpath->query("//id/@im:id");
$id      = $r->item(0)->value;

Try:

$sxml = new SimpleXMLElement($url);
for($i = 0;$i <=10;$i++){
$appid= $sxml->entry[$i]->id->attributes("im",TRUE);
echo $appid;
}

Need Your Help

Join operation on parent child in elasticsearch

elasticsearch

I have company and employee information.

Does the TCPServer + BaseRequestHandler in Python's SocketServer close the socket after each call to handle()?

python sockets

I'm writing a client/server application in Python and I'm finding it necessary to get a new connection to the server for each request from the client. My server is just inheriting from TCPServer an...