从XML代码中读取错误的字符

时间:2018-02-28 00:36:57

标签: php

我有一个PHP程序,它读取MySql数据库表并以XML格式打印该表。现在我想用这段代码将PHP文件(带有XML代码)读到我的C#应用​​程序:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/baza.php");

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader input = new StreamReader(response.GetResponseStream());
                //MessageBox.Show(input.ReadLine());
                DataSet dsTest = new DataSet();
                dsTest.ReadXml(input);
                dataGridView1.DataSource = dsTest;

但是我得到了一个例外,因为input.ReadLine()返回XML字符串但是有一些错误的字符(例如<替换为& lt;或"替换为& quot;)。 我知道我可以使用string.replace但这对我来说不是最好的解决方案。 这是我在浏览器中运行PHP代码时看到的内容:

<?xml version="1.0" encoding="UTF-8"?><MessageXML><row1><ID> 1 </ID><Ime> Pera </Ime><Prezime> Zdera </Prezime></row></MessageXML>

这就是我在MessageBox中得到的:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;MessageXML&gt;&lt;row1&gt;&lt;ID&gt; 1 &lt;/ID&gt;&lt;Ime&gt; Pera &lt;/Ime&gt;&lt;Prezime&gt; Zdera &lt;/Prezime&gt;&lt;/row&gt;&lt;/MessageXML&gt;

编辑: PHP代码:

<?php

$dbhost = '###';
$dbuser = '###';
$dbpass = '###';
$dbname = '###';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($conn, $dbname);

$query  = "SELECT * FROM nalog";
$result = mysqli_query($conn, $query);
echo htmlentities("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
echo htmlentities("<MessageXML>");

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
 echo htmlentities("<row1>"."<ID> {$row['id']} </ID>"."<Ime> {$row['ime']} </Ime>"."<Prezime> {$row['prezime']} </Prezime>"."</row>");
} 
echo htmlentities('</MessageXML>');
mysqli_close($conn);

?>

1 个答案:

答案 0 :(得分:0)

试用此功能,当您通过浏览器查看时,请按CTRL + U查看源页面

<?php

$dbhost = '###';
$dbuser = '###';
$dbpass = '###';
$dbname = '###';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($conn, $dbname);

$query  = "SELECT * FROM nalog";
$result = mysqli_query($conn, $query);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>;
echo "<MessageXML>";

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
 echo "<row1>"."<ID> {$row['id']} </ID>"."<Ime> {$row['ime']} </Ime>"."<Prezime> {$row['prezime']} </Prezime>"."</row>";
} 
echo '</MessageXML>';
mysqli_close($conn);

?>