json_encode()转义/使用\

时间:2016-05-25 19:21:30

标签: php html associative-array

我想在PHP数组中获取html。当我打印变量时,表格格式正确,但是输出到数组后,我的html结束标记中添加了反斜杠(例如:< / th>)。我不认为PHP中的斜杠需要有任何转义字符。当我print_r($table);它输出而不添加反斜杠并在我的浏览器中正确输出表但是当我将html表添加到PHP数组然后将数组作为JSON对象输出时,它将反斜杠添加到我的html结束标记如我浏览器下面的输出所示。任何想法都会有所帮助。

输出

{"data":{"success":"true","carriers":"1,2","table":"

CarrierId<\/th>

CarrierName<\/th>

1<\/td> UHC<\/td><\/tr> 
2<\/td> BlueCross<\/td><\/tr><\/table>"}} 

PHP:

<?php

// Show all information, defaults to INFO_ALL
//phpinfo();
/*environment:
OS: windows Server 2012 Standard build 9200
IIS: IIS version 8.0.9200.16384 --> Authentication - win auth ->enabled, Anonymou auth -->disabled, CGI -> Impersonate User = true
http://www.microsoft.com/web/downloads/platform.aspx
http://blogs.msdn.com/b/brian_swan/archive/2010/02/10/sql-server-driver-for-php-understanding-windows-authentication.aspx
SQL: - MS SQL server 10.5.1600
PHP: PHP version 5.4.26 for IIS, copy php_sqlsrv_54_ts.dll to C:\Program Files (x86)\PHP\v5.4\ext directroy from  

http://www.iis.net/learn/application-frameworks/install-and-configure-php-on-iis/install-the-sql-server-driver-for-php
php.ini file add
extension=php_pdo_sqlsrv_54_ts.dll

extension=php_sqlsrv_54_ts.dll
*/

//Connect to SQL with Authentication
$serverName = "PFIT-00-lync-03"; //serverName\instanceName
$connectionInfo = array( "Database"=>"spicewebinsurance", "UID"=>"spicerest", "PWD"=>"Password1");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     //echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}

$tsql= "select  convert(varchar,CarrierId) as CarrierId, CarrierName as CarrierName from  dbo.Carrier ";

//print_r($tsql) ;

$stmt=sqlsrv_query($conn, $tsql);

$table = "<table> <th>CarrierId</th><th>CarrierName</th>";

// Create table body 
if ($stmt) {
   $rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
      while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) 

{
$carriers[] = $row['CarrierId'];

$table .= "<tr><td>";

$table .= $row['CarrierId'];

 $table .= "</td><td>";

 $table .= $row['CarrierName'];

 $table .= "</td></tr>";

}
$table .= "</table>";

$carriers=implode(',', $carriers);

    $return=array(
        "success"=>"true",
        "carriers"=>$carriers,
        "table"=>$table
    );

}
else
{
    $return['success']=false;
}

echo '{"data":'.json_encode($return).'}';

sqlsrv_free_stmt( $stmt);
?>

1 个答案:

答案 0 :(得分:0)

我还没有看到为什么/被转义但使用选项JSON_UNESCAPED_SLASHES

echo '{"data":'.json_encode($return, JSON_UNESCAPED_SLASHES).'}';