如何使用PHP读取feeds内联标签?

问题描述 投票:1回答:1

我有一个下面的feed xml代码,显示人们的个人资料。我想在网站上使用一些信息,但我不能。

<?xml version="1.0"?>
<feed>
    <item system="15907" performancePage="http://platform.signaltofollow.com/performance/15907" avg_per_month="37.956" avatar="" username="FX_TM" country="Russian Federation" country_flag="http://platform.signaltofollow.com/api/assets/images/country/flags_round/flag_ru.png" />
    <item system="15915" performancePage="http://platform.signaltofollow.com/performance/15915" avg_per_month="13.9571" avatar="" username="InvestTrade77" country="Russian Federation" country_flag="http://platform.signaltofollow.com/api/assets/images/country/flags_round/flag_ru.png" />
    <item system="17315" performancePage="http://platform.signaltofollow.com/performance/17315" avg_per_month="12.5121" avatar="http://platform.signaltofollow.com/api/assets/images/user/6197fdd1-771f-429c-abfe-6ff232885658.JPG?_=cd5bc00c2c26fe659b58d722dade05d8" username="B4x" country="Poland" country_flag="http://platform.signaltofollow.com/api/assets/images/country/flags_round/flag_pl.png" />
    <item system="15289" performancePage="http://platform.signaltofollow.com/performance/15289" avg_per_month="10.6175" avatar="" username="Profittrading" country="Germany" country_flag="http://platform.signaltofollow.com/api/assets/images/country/flags_round/flag_de.png" />

</feed>

我想显示用户名和头像这个PHP代码,但我不能做到这一点。

<?php

 $url = "http://platform.signaltofollow.com/api/feed/top15TradeSystems";

 $invalidurl = false;
 if(@simplexml_load_file($url)){
  $feeds = simplexml_load_file($url);
 }else{
  $invalidurl = true;
  echo "<h2>Invalid RSS feed URL.</h2>";
 }

 $i=0;
 if(!empty($feeds)){

  echo "<h1>".$site."</h1>";
  foreach ($feeds->feed as $item) {

   $avatar = $item->item->avatar;
   $username = $item->item->username;

   if($i>=1) break;
  ?>
   <div class="post">
       <h2><?php echo $username; ?></h2>
    <img src="<?php echo $avatar; ?>">
   </div>

   <?php
    $i++;
   }
 }else{
   if(!$invalidurl){
     echo "<h2>No item found</h2>";
   }
 }
 ?>
php html xml rss feed
1个回答
0
投票

这是您的代码的简化值,只需足够突出目标。你可以根据自己的需要修改它。

<?php
$url = "http://platform.signaltofollow.com/api/feed/top15TradeSystems";
$feeds = simplexml_load_file($url);
$pars = $feeds->xpath('//feed/item[@username]');
foreach($pars as $node) {
    $un = $node->xpath('./@username')[0];
    $av = $node->xpath('./@avatar')[0];
    if (strlen ( $av )==0) {
    $av = 'No avatar';
       }
    echo "username: ". $un ."    avatar: ". $av . "<br>";     
}
?>

随机样本的输出,

username: InvestTrade77 avatar: No avatar
username: B4x avatar: http://platform.signaltofollow.com/api/assets/images/user/6197fdd1-771f-429c-abfe-6ff232885658.JPG?_=cd5bc00c2c26fe659b58d722dade05d8

等等

© www.soinside.com 2019 - 2024. All rights reserved.