Frage

I have just spent hours chasing one of the weiredest bugs I have come across. I wrote some Javascript code that generates some XML on the fly and sends it to a server running Apache and PHP.

The JS code snippet is:

<script>
function dummy() {
var str2 = '<?xml version="1.0" ?>';

...  add a bit more XML then send to server
}
</script>

On my desktop running WAMP this runs just fine. When I transfer it to my Raspberry Pi running LAMP, the server throws an Error 500 and refuses to serve the page.

In narrowing down which new code had broken the system I tried commenting out the block (using HTML commenting around the script section) containing the JS code to no avail. It wasn't until I actually deleted the line that it started working again. To be precise it is the 'version="1.0"' that it doesn't like.

What I don't understand is why the Apache server or PHP would even be looking at this line when it is serving the page to the browser, or even more so why it would be doing so if the block is commented out.

If I remove the 'version' part of the header, it then serves the page OK but the XML doesn't work.

I am very new to PHP & JS so I might be missing something obvious ??

I am running recent versions of all software.

Ideas please?

DG

War es hilfreich?

Lösung

As @drew010 pointed out in the comments, your php.ini probably has the short_open_tag directive on. This causes <? to be a valid open php tag, just like <?php.

With this directive on, php would parse these the same way:

var str2 = '<?xml version="1.0" ?>';
var str2 = '<?php xml version="1.0" ?>';

If you can't turn that directive off because you don't have access or one or more components requires it to be on, this workaround should suffice:

var str2 = '<' + '?xml version="1.0" ?>';

The reason that the code worked when you changed the line to this:

var str2 = '<?xml?>';

is that php is treating xml as a single statement. In this case the statement probably resolves to the string "xml" after a lookup of any constant named xml fails. Because you are not echoing the string, just evaluating it, your str2 variable should end up equating to "".

Andere Tipps

Another potential solution

Hello everyone, the question has been answered already, but here is another method that I think is worth mentioning. I chose this method because I wasn't running any JavaScript, and didn't want to have to start.

Error

The "<? ?>" tags are causing this to run as PHP

<?xml version="1.0" encoding="UTF-8" ?>

JavaScript Solution (already mentioned by Starson)

This breaks up tag "<? ?>"

var str2 = '<' + '?xml version="1.0" ?>';

PHP Solution (already mentioned by Starson)

This masks the "<? ?>" tag within PHP

<? echo '<?xml version="1.0" encoding="UTF-8" ?>';?>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top