Getting XML attributes in PHP

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

I've got this code:

$url = "";
$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">;uo=2</id>

Any suggestions?


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.


// Load XML
$url = "";
$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/>';


Try with xpath:

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


$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


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

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.