代码之家  ›  专栏  ›  技术社区  ›  Señor Reginold Francis

在PHP中从第三方页面检索XML

  •  0
  • Señor Reginold Francis  · 技术社区  · 16 年前

    我需要读取和解析数据从第三方网站发送XML数据。所有这些都需要在服务器端完成。

    4 回复  |  直到 16 年前
        1
  •  3
  •   Artefacto    16 年前

    您可以通过获取远程XML数据,例如。

    $xmldata = file_get_contents("http://www.example.com/xmldata");
    

    或与 curl . 然后使用 SimpleXML , DOM

        3
  •  1
  •   Marco Demaio    16 年前

    我建议你用 DOMDocument (PHP内联编译类) 下面的代码就是其强大功能的一个简单示例:

       /***********************************************************************************************
       Takes the RSS news feeds found at $url and prints them as HTML code.
       Each news is rendered in a <div class="rss"> block in the order: date + title + description. 
       ***********************************************************************************************/
       function Render($url, $max_feeds = 1000)
       {   
          $doc = new DOMDocument();
    
          if(@$doc->load($url, LIBXML_NOCDATA|LIBXML_NOBLANKS))
          {
             $feed_count = 0;
             $items = $doc->getElementsByTagName("item");
             //echo $items->length; //DEBUG
             foreach($items as $item)
             {              
                    if($feed_count > $max_feeds)
                       break;
    
                    //Unfortunately inside <item> node elements are not always in same order, therefor we have to call many times getElementsByTagName
                    //WARNING: using iconv function instead of utf8_decode because this last one did not convert properly some characters like apostrophe 0x19 from techsport.it feeds.
                    $title = iconv('UTF-8', 'CP1252', $item->getElementsByTagName("title")->item(0)->firstChild->textContent); //can use "CP1252//TRANSLIT"
                    $description = iconv('UTF-8', 'CP1252', $item->getElementsByTagName("description")->item(0)->firstChild->textContent); //can use "CP1252//TRANSLIT"
                    $link = iconv('UTF-8', 'CP1252', $item->getElementsByTagName("link")->item(0)->firstChild->textContent); //can use "CP1252//TRANSLIT"
    
                    //pubDate tag is not mandatory in RSS [RSS2 spec: http://cyber.law.harvard.edu/rss/rss.html]
                    $pub_date = $item->getElementsByTagName("pubDate"); $date_html = "";
                    //play with date here if you want
    
                    echo "<div class='rss'>\n<p class='title'><a href='" . $link . "'>" . $title . "</a></p>\n<p class='description'>" . $description . "</p>\n</div>\n\n";
    
                    $feed_count++;
            }
          }
          else
             echo "<div class='rss'>Service not available.</div>";
       }
    
        4
  •  0
  •   sushil bharwani    16 年前

    我已经使用simpleXML一段时间了。