2011-12-14 124 views

回答

1

這就是所謂的XML命名空間的前綴。 See this namespace tutorial

實際上,您並不匹配前綴,而是匹配前綴所代表的名稱空間。

你如何做到這一點完全取決於你用什麼來操縱XML。你不會說你在用什麼,但我會猜測你正在使用SimpleXML。

對於SimpleXML,默認情況下,對象訪問樹中只包含沒有名稱空間的節點。要獲得命名空間的元素,你需要去詢問他們:

$xml=simplexml_load_file('http://publishers.spilgames.com/rss?lang=en-US&tsize=1&format=xml&limit=100'); 

foreach($xml->entry as $game) { 
    $description = (string) $game->children('http://search.yahoo.com/mrss/')->description; 
    var_dump($description); 
} 

雖然它可能不是最好的選擇,在這種特殊情況下,也可以使用XPath命名空間節點更直接匹配:

$xml=simplexml_load_file('http://publishers.spilgames.com/rss?lang=en-US&tsize=1&format=xml&limit=100'); 

$NS = array(
    'media' => 'http://search.yahoo.com/mrss/', 
); 
foreach ($NS as $prefix => $uri) { 
    $xml->registerXPathNamespace($prefix, $uri); 
} 

foreach($xml->entry as $entry) { 
    // match the first media:description element 
    // get the first SimpleXMLElement in the match array with current() 
    // then coerce to string. 
    $description = (string) current($entry->xpath('media:description[1]')); 
    var_dump($description); 
} 

下面是一個更完整的例子,它也讓你的代碼稍微有些變了。

$xml=simplexml_load_file('http://publishers.spilgames.com/rss?lang=en-US&tsize=1&format=xml&limit=100'); 

// This gets all the namespaces declared in the root element 
// using the prefix as declared in the document, for convenience. 
// Note that prefixes are arbitrary! So unless you're confident they 
// won't change you should not use this shortcut 
$NS = $xml->getDocNamespaces(); 

$games = array(); 
foreach($xml->entry as $entry) { 
    $mediaentry = $entry->children($NS['media']); 
    $games[] = array(
     // to get the text value of an element in SimpleXML, you need 
     // explicit cast to string 
     'name' => (string) $entry->title, 
     // DO NOT EVER use array-access brackets [] without quoting the string in them! 
     // I.e., don't do "$array[name]", do "$array['name']" 
     // This is a PHP error that happens to work. 
     // PHP looks for a *CONSTANT* named HREF, and replaces it with 
     // string 'href' if it doesn't find one. This means your code will break 
     // if define('href') is ever used!! 
     'link' => (string) $entry->link['href'], 
     'description' => (string) $mediaentry->description, 
    ); 
} 
$it = count($games); // there is no need for your $it+1 counter! 

// $games now has all your data. 
// If you want to insert into a database, use PDO if possible and prepare a query 
// so you don't need a separate escaping step. 
// If you can't use PDO then do: 
// $escapedgame = array_map('mysql_real_escape_string', $thegame); 
2

裹在{}字符串:

$description = mysql_real_escape_string($game->{'media:description'}); 

見:Strings: Complex (curly) syntaxVariable variables

+0

感謝您的幫助。錯誤消失了。但是,當我嘗試獲取中的數據時,我似乎沒有得到任何結果。 – 2011-12-14 23:49:39