2011-12-14 2 views
2

У меня есть фид, но есть элемент : в элементе, значение которого я хочу получить. Что я делаю?Чтение XML-узлов с помощью:

Feed: http://publishers.spilgames.com/rss?lang=en-US&tsize=1&format=xml&limit=100

foreach($xml->entry as $game) {  
    $it = $it+1; 
    $name = mysql_real_escape_string($game->title);   
    $link = $game->link[href]; 
    $description = mysql_real_escape_string($game->media:description); 

ответ

1

Это то, что называется префикс пространства имен XML. See this namespace tutorial.

Фактически вы не соглашаетесь на префикс, который вы сопоставляете в пространстве имен, на котором стоит префикс.

Как вы это делаете, полностью зависит от того, что вы используете для управления xml. Вы не говорите, что используете, но я думаю, вы используете SimpleXML.

С SimpleXML по умолчанию в дерево доступа к объекту включены только узлы без пространства имен. Чтобы получить Namespaced элементы, вам нужно явно задать для них:

$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

Wrap строка в {}:

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

См: Strings: Complex (curly) syntax и Variable variables

+0

Спасибо за помощь. Ошибка исчезла. Но когда я пытаюсь извлечь данные в , я, похоже, не получаю результата. –

+0

Это не сработает, так как он имеет дело с пространствами имен в SimpleXML (скорее всего), хотя урок на переменных переменных стоит. –

Смежные вопросы