在PHP中获取XML属性

在PHP中获取XML属性,php,xml,simplexml,Php,Xml,Simplexml,看了其他一些关于这个的帖子,但是没有什么乐趣 我有这个密码: $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

看了其他一些关于这个的帖子,但是没有什么乐趣

我有这个密码:

$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";
$url=”http://itunes.apple.com/us/rss/toppaidapplications/limit=10/genre=6014/xml";
$string=文件内容($url);
$string=preg_replace(“/(]*>)/”、“$1$2$3”、$string);
$xml=simplexml\u load\u string($string);
foreach($xml->entry as$val){
回显“结果:”..val->attributes()。“\n”;
但我不能得到任何结果。 我特别感兴趣的是获取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>
http://itunes.apple.com/us/app/wipeout/id549592189?mt=8&;uo=2

有什么建议吗?

尝试使用
xpath

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

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

$sxml=新的SimpleXMLElement($url);
对于($i=0;$i条目[$i]->id->attributes(“im”,TRUE);
echo$appid;
}

不要用正则表达式操纵html/xml。你只是在自找麻烦。你应该阅读。它与html有关,但xml也适用。对于正则表达式,也许这已经解决了,但请参见:@SnowCrash:不要总是相信PHP.net上的注释,它们是由用户发布的,可能不正确。在这种情况下,该注释是错误的。SimpleXML可以很好地使用XML名称空间,您只需要知道如何使用它们。请参阅:和@snow crash“在PHP中为表达式添加前缀时,将忽略该表达式可能生成的任何错误消息。”在这种情况下,在处理格式错误的下载文档时,忽略PHP警告会有所帮助。
$sxml = new SimpleXMLElement($url);
for($i = 0;$i <=10;$i++){
$appid= $sxml->entry[$i]->id->attributes("im",TRUE);
echo $appid;
}