A transpiler that converts JavaScript code to PHP. This tool enables running JavaScript logic on the server-side using PHP.
js2php is a JavaScript-to-PHP transpiler built with Babel. It transforms JavaScript AST (Abstract Syntax Tree) into equivalent PHP code, providing a compatible runtime environment with JavaScript's core classes and utilities.
.
├── src/
│ └── transform.js # Main transpiler logic
└── php/
├── runtime.php # Runtime initialization
├── classes # JavaScript class implementations
├── globals # Global object implementations
├── helpers # Utility functions and operators
└── modules # Module implementations (fs, http, etc.)
- Parse - Uses Babel parser to convert JavaScript to AST
- Traverse - Walks the AST using Babel traverse
- Transform - Converts each node to PHP code, handling:
- Variable declarations and assignments
- Function calls and method invocations
- Object and array literals
- Operators with JavaScript semantics
- Control flow statements
- Generate - Outputs valid PHP code
The current implementation prioritizes correctness and compatibility with JavaScript semantics. Because of this, much of the JavaScript runtime is emulated in PHP including objects, arrays, prototypes, operators and etc.
This means:
- Execution is considerably slower than native PHP, since operations are routed through compatibility layers.
The long-term plan is to move toward generating idiomatic PHP rather than fully emulating JavaScript behavior. Planned improvements include:
- Using native PHP equivalents for JavaScript built-ins
- Mapping JS arrays/objects directly to PHP structures
- Eliminating wrapper classes where possible
- Optimizing operators and control flow
- Reducing runtime overhead
MIT License
Copyright (c) 2025 Phact
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contributions are welcome! Please feel free to submit issues and pull requests.