How to echo xml file in php

前端 未结 10 814
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 04:37

How to print an xml file to the screen in php?

This is not working:

$curl = curl_init();        
curl_setopt ($curl, CURLOPT_URL, \'http://rss.news.y         


        
相关标签:
10条回答
  • 2020-11-29 05:02

    If anyone is targeting yahoo rss feed may benefit from this snippet

    <?php
        $rssUrl="http://news.yahoo.com/rss/topstories";
        //====================================================
        $xml=simplexml_load_file($rssUrl) or die("Error: Cannot create object");
        //====================================================
        $featureRss =  array_slice(json_decode(json_encode((array) $xml ),  true ), 0 );
     /*Just to see what is in it 
    use this function PrettyPrintArray() 
    instead of var_dump($featureRss);*/
    
        function PrettyPrintArray($rssData, $level) {
        foreach($rssData as $key => $Items) {
        for($i = 0; $i < $level; $i++)
        echo("&nbsp;");
        /*if content more than one*/
        if(!is_array($Items)){
        //$Items=htmlentities($Items); 
        $Items=htmlspecialchars($Items);
        echo("Item " .$key . " => " . $Items . "<br/><br/>");
        }
        else 
        {
        echo($key . " => <br/><br/>");
        PrettyPrintArray($Items, $level+1);
        }
        }
        }
        PrettyPrintArray($featureRss, 0);
    ?>
    

    You may want to run it in your browser first to see what is there and before looping and style it up pretty simple

    To grab the first item description

    <?php
        echo($featureRss['channel']['item'][0]['description']);
    ?>
    

    You can see a demo here

    0 讨论(0)
  • 2020-11-29 05:03

    You can use the asXML method

    echo $xml->asXML();
    

    You can also give it a filename

    $xml->asXML('filename.xml');
    
    0 讨论(0)
  • 2020-11-29 05:10

    This worked for me:

    echo(header('content-type: text/xml'));
    
    0 讨论(0)
  • 2020-11-29 05:19

    To display the html/xml "as is" (i.e. all entities and elements), simply escape the characters <, &, and enclose the result with <pre>:

    $XML = '<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <foo>ó</foo>
        <bar>&#xF3;</bar>
    </root>';
    
    $XML = str_replace('&', '&amp;', $XML);
    $XML = str_replace('<', '&lt;', $XML);
    echo '<pre>' . $XML . '</pre>';
    

    Prints:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <foo>ó</foo>
        <bar>&#xF3;</bar>
    </root>
    

    Tested on Chrome 45

    0 讨论(0)
提交回复
热议问题