du7999 2018-03-14 11:38 采纳率: 100%
浏览 30
已采纳

PHP - 处理RSS中的破折号

I'm fairly new to PHP, but I'm trying to parse parts of an RSS feed to render over to HTML. The issue is that just about every tag in the feed has a dash in it and that's making it hard to deal with. I tried doing something like $home->{'pub-code'}->{'ad-type'} etc. but that didn't seem to work either. What I have so far is the following:

    foreach ( $topRSS->channel->item as $home ) 
         {$returnValue .= "<li><span class=\"Title\">".$home->pub-code->ad-type->account-name."</span><br><a class=\"Link\" href=\"#\">".$home->pub-code->ad-type->ad-content."</a></li>";
         $counter++;
         if ($counter > 4)
             break;
         }

which is an attempt at iterating over an RSS feed with items that look like :

 <item>
  <pub-code>
    <ad-type>
      <cat-code>Jobs</cat-code>
      <class-code/>
      <ad-number>12345</ad-number>
      <ad-number>12345</ad-number>
      <start-date>03/14/2018</start-date>
      <image><image/>
      <account-number>12345</account-number>
      <account-name>GENE BROWN</account-name>
      <addr-1>12533 WALSINGHAM RD</addr-1>
      <addr-2/>
      <city>LARGO</city>
      <state>FL</state>
      <postal-code>33774</postal-code>
      <ad-content> Content</ad-content>
    </ad-type>
  </pub-code>
 </item>

I'm sure this is a simple syntax thing, but I can't manage to find documentation on it anywhere.

Any help would be greatly appreciated.

Thanks!

展开全部

  • 写回答

1条回答 默认 最新

  • douqiao8032 2018-03-14 11:44
    关注

    Per the basic usage section for SimpleXML:

    Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

    Example #3 Getting <line>

    <?php include 'example.php';
    
    $movies = new SimpleXMLElement($xmlstr);
    
    echo $movies->movie->{'great-lines'}->line; ?>
    

    This relies on PHP's "variable variables" functionality.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?