Home > front end >  How to get and pass a XML string on php to java script from mysql
How to get and pass a XML string on php to java script from mysql

Time:10-18

So I got this code:

                  <input type='button' value='clickme' onclick='download(\"" . $rowtable['Protocolo'] . ".xml\",\"" . $rowtable['XML']. "\");'/></input>
                  <script>
                  function download(filename, text) {
                    var pom = document.createElement('a');
                    pom.setAttribute('href', 'data:text/plain;charset=utf-8,'   encodeURIComponent(text));
                    pom.setAttribute('download', filename);
                
                    if (document.createEvent) {
                        var event = document.createEvent('MouseEvents');
                        event.initEvent('click', true, true);
                        pom.dispatchEvent(event);
                    }
                    else {
                        pom.click();
                    }
                }
                  </script>

It get 2 result from my DB that is a String(Protocolo) and a TEXT(XML). But the thing is my TEXT(XML) data look like this:

<?xml version="1.0" encoding="UTF-8"?><enviNFe versao="4.00" xmlns="asdasdasdasdasd"><idLote>1</idLote><indSinc>1</indSinc><NFe xmlns="asdsdasadsad">

As u can see, it have alot of " on it. And it kind bugs, the code. So my question is, how can I transform all this $rowtable['XML'] into a proper string. So I can pass it to the JS so i can download it.

If u have any better way of downloading this XML data from my DB is welcome aswell.

CodePudding user response:

You could encode the xml in php with urlencode, and use it's value directly in javascript.

<input type='button' value='clickme' onclick='download(\"" . $rowtable['Protocolo'] . ".xml\",\"" . urlencode($rowtable['XML']). "\");'/></input>
<script>
function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,'   text);
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
</script>

CodePudding user response:

You're missing the escaping for Javascript and HTML in the button input attributes. Using urlencode() or base64_encode() (in PHP) would encode the special characters so they can not break the JS or HTML code.

However if you use an a element you can do this without the JavaScript.

<html>
  <body>
  <?php
    $data = '<foo>Example String</foo>';
    $fileName = 'demo.xml';
  ?>
    <a
      class="DownloadButton"
      href="data:text/plain;charset=utf8,<?=urlencode($data)?>"
      download="<?=htmlspecialchars($fileName)?>">Download</a>
  </body>
</html>

The data is encoded and put into a Data URL.

  • Related