PHP is run on server side and not Client side like JavaScript, you need to dynamically load the php to do this. (preferably with ajax)
A simple solution would be to put the php code into a new file called X.js
then create an empty <script id="loadscript" src="#">
tag then change the src with javascript
document.getElementbyId("loadscript").src="https://stackoverflow.com/questions/16225445/x.js";
would run the code
solved Can’t call PHP function from Javascript [duplicate]