Problem with rss feed created in php

Discussion in 'PHP' started by PinoyIto, May 3, 2007.

  1. #1
    I have created a php base rss feed , but the feed getting error "XML Parsing Error: not well-formed"

    I notice that if there are special characters like & , < , > , ', " and others the problem is showing but if no special characters there is no error.

    Here is my sample code :

    
    <?php
    $data ="<item>
                              <title>title of feed</title>
                              <link>link of feed</link>
                              <description>description</description>
    			  </item>";
    
    header("Content-type: application/xml; charset=ISO-8859-1");
    echo '<?xml version="1.0" encoding = "UTF-8" ' ."?>\n";
    ?>
    
    <rss version="2.0">
    <channel>
    <title>Title here</title>
    <link>site url</link>
    <description>description here</description>
    <?=$data?>
    </channel>
    
    
    Code (markup):
     
    PinoyIto, May 3, 2007 IP
  2. designcode

    designcode Well-Known Member

    Messages:
    738
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    118
    #2
    Where are these characters? In tags or or Tag data?

    Try using this

    $data ="<item>
    <title>".htmlspecialchars("title of feed")."</title>
    and so on....
     
    designcode, May 3, 2007 IP
  3. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #3
    A useful function I use for converting special characters when creating XML files. Courtesy of user comments on php.net:
    function xmlentities($string, $quote_style=ENT_QUOTES)
    {
        static $trans;
        if (!isset($trans)) {
            $trans = get_html_translation_table(HTML_ENTITIES, $quote_style);
            foreach ($trans as $key => $value)
                $trans[$key] = '&#'.ord($key).';';
            // dont translate the '&' in case it is part of &xxx;
            $trans[chr(38)] = '&';
        }
        // after the initial translation, _do_ map standalone '&' into '& #38;'
        return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","& #38;" , strtr($string, $trans));
    }
    PHP:
    EDIT: vB's parser won't let me post &#38; without converting to &. Just remove the space from the return value in the preg_replace line.
     
    rodney88, May 4, 2007 IP