PHP:读取一个 php url 作为 xml 并解析它 [英] PHP: read a php url as xml and parse it

查看:29
本文介绍了PHP:读取一个 php url 作为 xml 并解析它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的网址 http://somedomain.com/frieventexport.php 如果我查看网站的源代码,这个网址的内容是一个纯 XML 结构:

i got a url like this one http://somedomain.com/frieventexport.php and the content of this url is a plain XML structure if I check out the source-code of the site:

如何解析这个 URL 并在 PHP 中使用它?这个脚本给了我一个错误......加载 XML 时出错".

How can I parse this URL and use it in PHP? This script gives me an error… "Error loading XML".

<?php

    $xml_url = "http://somedomain.com/frieventexport.php";

    if (($response_xml_data = file_get_contents($xml_url))===false){
        echo "Error fetching XML\n";
    } else {
       libxml_use_internal_errors(true);
       $data = simplexml_load_string($response_xml_data);
       if (!$data) {
           echo "Error loading XML\n";
           foreach(libxml_get_errors() as $error) {
               echo "\t", $error->message;
           }
       } else {
          print_r($data);
       }
    }

?>

推荐答案

我认为最好的选择之一是使用 CURL 从 url 获取原始 XML 数据:

One of the best options in my opinion is to use CURL to get the raw XML data from the url:

$curl = curl_init();
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_URL, "http://somedomain.com/frieventexport.php" );

$xml = curl_exec( $curl );
curl_close( $curl );

然后您可以使用 DOMDocument 来解析 xml:

You can then use DOMDocument to parse the xml:

$document = new DOMDocument;
$document->loadXML( $xml );

我还建议在您的 XML 中使用 <![CDATA[]> 标签.请阅读以下内容:

I would also recommend using <![CDATA[]> tags in your XML. Please read the following:

  • What does <![CDATA[]]> in XML mean?
  • CDATA Sections in XML

更多关于 DOMDocument 和用法的信息

More information about DOMDocument and usage

这篇关于PHP:读取一个 php url 作为 xml 并解析它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆