Чтение XML-узлов с помощью: - PullRequest
2 голосов
/ 15 декабря 2011

У меня есть фид, но в пункте, чье значение я хочу получить, есть :.Что мне делать?

Лента: 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);  

Ответы [ 2 ]

2 голосов
/ 15 декабря 2011

Обернуть строку в {}:

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

См .: Строки: сложный (фигурный) синтаксис и Переменные

1 голос
/ 15 декабря 2011

Это то, что называется префиксом для пространства имен xml. См. Это учебное пособие по пространству имен .

На самом деле вы не совпадаете с префиксом, вы совпадаете с пространством имен, за которым стоит префикс.

Как вы это делаете, полностью зависитна что вы используете для манипулирования 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);
...