Php to javascript compiler

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

convert php code to javascript code that run on browser

scrawler-archive/php2js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Convert php code to javascript code that can run on browser

package can be installed via composer

composer require piqon/php2js 

If You want to create a copiled javascript file , you can run the following code:

 include __DIR__ . '/vendor/autoload.php'; /* * Replace test.php with path of your input php file * Replace test.js with path for your js file output */ \PHP2JS\PHP2JS::compileFile(__DIR__.'/test.php',__DIR__.'/test.js');

If you just want to convert a small block of code , you can run the following code:

 include __DIR__ . '/vendor/autoload.php'; $code pl-s"> $name='1'; echo 'hi'; " \PHP2JS\PHP2JS::compile($code);
 $name = 'Pranjal'; $cars = ['BMW','Audi']; $cars->push('Ferrari'); echo $name; echo $cars; function click()< echo 'button clicked!'; >
let name = 'Pranjal'; let cars = ['BMW', 'Audi']; cars.push('Ferrari'); console.log( name); console.log( cars); function click()  console.log( 'button clicked!'); >

This was designed to convert php scripts to javascript code , this might not work with full blown php classes ! You can call javascript functions like console.log etc right from your php code and it will work as expected in the browser. This compiler does not support magic variables and magic functions of PHP.

  • Added support for import : include ‘test’ now converts to import test from ‘./test.js’ You can also use import_from() php function to define path of module. Example:
import_from('test','./component/test.js');
import test from './component/test.js';
// @async function abc()< return 'hi'; >
async function abc() return 'hi'; >

About

convert php code to javascript code that run on browser

Источник

php.js

This library reads PHP code and transforms it into JavaScript code which can be run in the PHP VM in this library, resulting in same results as with PHP. It starts by tokenizing the PHP code into tokens, which it then uses to build an AST tree. Once the tree has been constructed, the script compiles it into JavaScript that can be interpreted by the VM and then executes it. Any additional unconverted code that gets executed within the VM, such as eval or lambda functions will go through the same process before being executed.

The code can be directly run in your browser, meaning you can execute php code straight out of your browser! It can also be run on node.js, but strongly recommend not to due to potential security issues.

As it might not be as self explanatory, this project is purely a proof-of-concept and should by no means be considered to be used in any sort of production environment.

Some examples

Usage

var engine = new PHP (''); console.log( engine.vm.OUTPUT_BUFFER); // the outputted buffer from the script

The code is by default run synchronously so the output will be immidiately readable upon the engine finishing execution. Alternatively, the VM can be set to run under a web worker as well, in which case a callback function will need to be provided.

Status

I took a test driven approach to developing this library, which means that I have been mostly focusing on getting the php unit tests (which PHP uses itself) to work correctly. If a certain functionality hasn’t been a part of the base unit tests (around 670 in total), it most likely won’t work or only works partially. Additionally, only a fraction of module functions have been implemented, and even for the ones that have been, many of them are only partially implemented (i.e. signature checks haven’t really been implemented to any functions, although user created functions support them). However, additional functions can easily be added, as they can be written in PHP and have them compiled into JavaScript.

The current status of the passing tests can be seen here. I’ll be the first admit that there are still a lot of bugs, but considering the complexity of the language, it is well on its way.

Questions & Comments

If you encounter a bug, please feel free to post it on GitHub. For questions or comments, you can contact me at Twitter @niklasvh or Google Plus

Niklas von Hertzen

Twitter Google+ Facebook Github LinkedIn

Hosted on GitHub Pages using the Dinky theme

Источник

looking for transpiler: php to javascript [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

i wonder, if there’s any transpiler available, which converts (simple) php code to javascript? what i am not looking for is ajax stuff or javascript libraries imitating php functionality, but i am looking for a translater, which is able to generate javascript code from php code (similar of what google is doing with GWT and the java-to-javascript transpiler). thanks!

afaik GWT is a compiler, not a transpiler; transpilers in general aren’t terribly useful and will most likely only work for special cases because of the differences in type systems/standard libraries

I prefer the term cross-compiler, too, but the term transpiler is starting to get used more and more often these days. We’ll see if it catches on. At least in the JavaScript world, I think it just might. But I agree with your sentiment. I tend to think CoffeeScript to JavaScript is a transpiler, but Java to JavaScript, not so much. Others disagree. We’ll see what people are saying a year from now.

Yes, I wrote one: gitlab.com/kornelski/babel-preset-php It produces readable source with approximate semantics.

2 Answers 2

The uniter php to js transpiler can do this: http://asmblah.github.io/uniter/

You can use something like this: http://www.harmony-framework.com/
But notice, that Javascript has lots of security issues PHP avoids. And straight conversion is not always possible for Database-related function calls or some other PHP extensions

my comment to the question applies: eg, harmony translates array($a => ‘foo’) to ; depending on the problem harald is trying to solve, something like haxe.org which can compile to both PHP and JS might be a better solution

mmm — harmony seems to be a little outdated — the webpages last change was in 2008. do you know, if they are still working on it? i think harmony would fit my needs better than haxe, even though haxe seems to be very advanced. but i don’t know how i would integrate haxe with my app, because my app is already implemented in php . only the php->javascript part is missing, which would help speed up development and make things more convenient .

@harald: if you look at the svn commit feed of harmony ( code.google.com/feeds/p/harmony-framework/svnchanges/basic ), you’ll see that development is slow, but I don’t think it’s dead; the documentation an how to wrap PHP code for haxe seems somewhat. incomplete: haxe.org/doc/php/extern_libraries ; if all that’s missing from your application is some JS, porting it to haxe will be overkill

i mark this as answered, because this harmony thing seems at least to be a very good starting point for this. thanks you both!

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

php2js is a tool that can automatically translate PHP code into Javascript code.

dan-da/php2js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

php2js is a tool that can automatically translate PHP code into Javascript code.

I originally wrote this back in 2008 and am just now (2015) getting around to releasing it on github.

I wrote this as part of a larger project, phpwt, which is a PHP port of pyjamas, which is itself a port of GWT to python.

The code has not been maintained for years and the language translation will never be 100% due to differing language features and libraries, but I am releasing it anyway in case someone finds it useful.

An example of code translation:

function test1() < $arr = array('colors' => array("red" => 'Red', 'green' => "Green"), 'candies' => array('twix','snickers', 'jolly ranchers'), 'holiday' => 'christmas' ); $arr['planet'] = 'Earth'; $okay = $arr['colors']['red'] == 'Red' && $arr['candies'][1] == 'snickers' && $arr['holiday'] == 'christmas'; echo "Test that assoc array init and deref works \n"; echo 'Result: ' . (($okay === true) ? 'pass' : 'fail') . "\n\n"; > test1();

Translated Javascript code

test1 = function()  var arr = ___array([ "__kv", "colors",___array([ "__kv", "red","Red"],[ "__kv", "green","Green"])],[ "__kv", "candies",___array("twix","snickers","jolly ranchers")],[ "__kv", "holiday","christmas"]); arr["planet"] = "Earth"; var okay = arr["colors"]["red"]=="Red"&&arr["candies"][1]=="snickers"&&arr["holiday"]=="christmas"; ___echo("Test that assoc array init and deref works
\n"
); ___echo("Result: "+((okay===true)?"pass":"fail")+"\n\n"); > test1();

Supports standard PHP functions!

A cool thing is that most of the built-in PHP functions work as expected after translation to javascript.

For example, sprintf(), extract(), implode(), date(), array_keys(), array_merge() and on and on. These work because the translator automatically includes the php.js library, from the fine folks at phpjs.org.

This tool can be useful any time you have code already written in PHP that you would like to translate into JS.

Typically this would be when moving code from server-side to the browser.

One possible use case could be to have a set of validation routines that are written in PHP for the server, but a build system automatically translates them to javascript so that the same validation logic can be made client side without requiring server interaction.

note: spidermonkey (or nodejs) is only needed for running the test cases from the command line.

  1. Clone the php2js repo.
  2. Install PHC if not already present.
  3. Install Spidermonkey if not already present. On Ubuntu, just
sudo apt-get install libmozjs-24-bin 
cd phpwt_tests ./gen_all_tests 

Note: as of this writing, 88 test cases pass, and 11 are failing.

php2js -- a tool to translate PHP code into JS code. Usage: php2js [options] [include-paths] Options: --help Display usage info. --exclude-phpjs Do not include phpjs javascript library in output. 

Translated javascript will be printed to STDOUT and may be redirected to a file.

By default, the generated javascript will contain the phpjs function library and your translated code will be at the end.

In a future version, hopefully we can remove any unused library functions to keep the generated output smaller.

About

php2js is a tool that can automatically translate PHP code into Javascript code.

Источник

Читайте также:  Test Javascript
Оцените статью