首页 > 解决方案 > 如何使用 PHP 读取提要内联标签

问题描述

我有一个下面的提要 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>";
   }
 }
 ?>

标签: phphtmlxmlrssfeed

解决方案


这是代码的简化值,足以突出显示目标。您可以明显地修改它以满足您的需求:

<?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

等等


推荐阅读