在PHP中获取XML属性 [英] Getting XML attributes in PHP

查看:53
本文介绍了在PHP中获取XML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看了其他几篇关于这个的SO帖子,但没有什么乐趣。

我有这样的代码:

$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() . "
";

但我得不到任何结果。 我特别感兴趣的是获取此片段中的ID值为549592189:

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

有什么建议吗?

SimpleXML

推荐答案为您提供了一种向下钻取XML结构并获取所需元素的简单方法。不需要正则表达式,无论它做什么。

<?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/>';
}

演示:http://codepad.viper-7.com/qNo7gs

这篇关于在PHP中获取XML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆