将XML转换为JavaScript中的多行字符串

时间:2019-01-01 19:42:42

标签: javascript xml string parsing

我有一个xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<productenv:Envelope>
    <productenv:Body>
        <products>
            <productName>TestProduct</productName>
            <productPrice>50.00</productPrice>
        </products>
    </productenv:Body>
</productenv:Envelope>

我正在使用PHP从外部服务器接收此文件。然后将XML传递到javascript文件。这是javascript对XML存储在其中的变量的作用:

<script type="text/javascript">
  var result = "<?php echo $result; ?>"; // $result is the variable that sorts the xml file
  console.log(result);
</script>  

运行代码时,出现以下错误:未捕获的SyntaxError:意外的数字。这是因为XML变成了字符串,但是1.0和UTF-8周围的双引号使文件混乱。

有什么办法可以使XML成为我可以解析的多行字符串?

1 个答案:

答案 0 :(得分:2)

假设$result字符串不包含任何反引号字符,则可以尝试使用javascript's template literals

<script type="text/javascript">
  var result = `<?php echo $result; ?>`; // $result is the variable that sorts the xml file
  console.log(result);
</script>