在XML输出中随机出现的无效字符,包括在标记中


Invalid characters appearing at random in XML output, including within the tags

我有一个生成XML文档的php脚本,但是输出有一个奇怪的问题。

我得到无效字符似乎在整个文档中随机,甚至在标签本身?例如:

<id><![CATA[JS-DWLG001]]></id>

我不确定这将如何在浏览器中呈现,所以如果你看不到它,无效字符正在替换'CDATA'中的'D'。

任何想法?

编辑:下面是生成xml的业务代码:

<?
// variables and arrays populated here from db
?>
<job>
                <title><![CDATA[<?=$field['vac_Title']?>]]></title>
                <date><![CDATA[<?=date("D, j M Y g:i:s",$stamp)." GMT"?>>]]></date>
                <referencenumber><![CDATA[<?=$field['vac_Ref']?>]]></referencenumber>
                <url><![CDATA[<?=site_URL.parse_job_path($field['vac_Title'],$key)?>]]></url>
                <company><![CDATA[<?=$field['vac_advertiser_name']?>]]></company>
                <city><![CDATA[]]></city>
                <state><![CDATA[<?=$field['vac_locs']?>]]></state>
                <country><![CDATA[UK]]></country>
                <postalcode><![CDATA[]]></postalcode>
                <description><![CDATA[<?=$field['vac_Description']?>]]></description>
                <salary><![CDATA[<?-$field['vac_Salary-Range']?>]]></salary>
                <education><![CDATA[<?=$education_level?>>]]></education>
                <jobtype><![CDATA[<?=$emp_type?>]]></jobtype>
                <category></category>
                <experience></experience>
            </job>

在php脚本中,当我们尝试使用附加字符串生成XML时,通常会产生问题。输出可能包含一些特殊字符和unicode字符。所以使用core php提供的库总是一个好主意。就像您可以使用DOM XML生成XML一样。这也将处理您的特殊字符和格式。下面是带有DOM XML

的示例代码
<?php
$books = array();
$books [] = array(
    'title' => 'PHP Hacks',
    'author' => 'Jack Herrington',
    'publisher' => "O'Reilly"
    );
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement( "books" );
$doc->appendChild( $r );
foreach( $books as $book )
{
    $b = $doc->createElement( "book" );
    $author = $doc->createElement( "author" );
    $author->appendChild(
        $doc->createTextNode( $book['author'] )
        );
    $b->appendChild( $author );
    $title = $doc->createElement( "title" );
    $title->appendChild(
        $doc->createTextNode( $book['title'] )
        );
    $b->appendChild( $title );
    $publisher = $doc->createElement( "publisher" );
    $publisher->appendChild(
        $doc->createTextNode( $book['publisher'] )
        );
    $b->appendChild( $publisher );
    $r->appendChild( $b );
}
header('Content-type: text/xml;charset=UTF-8');
echo $doc->saveXML();
?>

希望这将解决您的问题