rss parsing DOMDocument in PHP

旧时模样 提交于 2019-12-24 19:15:27

问题


I'm trying to get all categories and push them into my array, so far I'm doing it this way:

  $doc = new DOMDocument();
  $doc->load('myxml.xml');
  $arr = array();
  foreach ($doc->getElementsByTagName('item') as $node) {
    $items = array ( 
      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
      'date' => $node->getElementsByTagName('category')->item(0)->nodeValue
      );
    $arr [] = $items ;
  }

This works if we have only 1 cat, however, my xml has several categories per item. What would be a good way of doing this?

<item>
  <title>Submit</title>
  <category>Foo</category>
  <category>Bar</category>
</item> 

Thanks


回答1:


This should help:

$doc = new DOMDocument();
$doc->load('myxml.xml');
$arr = array();
foreach ($doc->getElementsByTagName('item') as $node) {
    $item = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'date' => array()
    );

    foreach($node->getElementsByTagName('category') as $catNode)
    {
        $item['date'][] = $catNode->nodeValue;
    }

    $arr[] = $item;
}
  • Christian



回答2:


You need nested loops:

$doc = new DOMDocument();
$doc->load('myxml.xml');
$arr = array();

foreach ($doc->getElementsByTagName('item') as $itemNode) {
    $items = array( 
        'title' => $itemNode->getElementsByTagName('title')->item(0)->nodeValue,
        'date'  => array()
    );

    foreach ($itemNode->getElementsByTagName('category') as $categoryNode) {
        $items['date'][] = $categoryNode->nodeValue;
    }

    $arr[] = $items;
}


来源:https://stackoverflow.com/questions/4336491/rss-parsing-domdocument-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!