Karl Herrick

A technologist and web developer | Posts about technology encountered along the journey.

PHP Web Component

WebAssembly becomes the fourth language for the Web which allows code to run in the browser

I’ve been enjoying learning a little bit more about WebAssembly. The journey has been long and a bit sporadic as my first introduction to the concepts were with Emscripten shortly after the release of asm.js. Since then, the scope of the project seems to have widened and the landscape has grown — it’s more than the browser [1, 2, 3, 4].

With that said, here are a few projects that have caught my attention for use in that environment:

…wait, PHP in the browser. I’ve always wanted that.

So just for fun I decided to clone PIB, build with the latest versions, and wrap it up as Web Component called <x-php>. In my opinion, the most exciting part is defining the contents of the PHP script inside of an actual HTML script tag and passing it along inside of the default slot. The MIME type I chose for the type attribute is debatable, but it seems to work in the browsers I’ve tested it in.

Try it out live in the browser or in an HTML document:

<x-php>
  <script type="text/php">
  <?php
    $it = new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator('.')
    );

    foreach ($it as $name => $entry) {
      echo "$name <br/>";
    }
  </script>
</x-php>
<script>
  window.__XPHP_REMOTE_PACKAGE_BASE =
  'https://kherrick.github.io/x-php/assets/'
</script>
<script
  src="https://kherrick.github.io/x-php/dist/esm/XPHP.js"
  type="module"
></script>