Skip to content

Instantly share code, notes, and snippets.

@jimanx2
Last active April 26, 2024 03:14
Show Gist options
  • Select an option

  • Save jimanx2/0c42333525c0c06ec646e9c7bdb2b315 to your computer and use it in GitHub Desktop.

Select an option

Save jimanx2/0c42333525c0c06ec646e9c7bdb2b315 to your computer and use it in GitHub Desktop.
Feeble attempt to mimic `jq` functionality with PHP input. Usage: `echo filename.php | phpq '$.attr1.subattr1'`
#!/usr/bin/env php
<?php
$syntax = !empty($argv[1]) ? $argv[1] : "\$";
$input = preg_replace("/^<\?php/", "", trim(file_get_contents("php://stdin")));
$defvars = array_keys(get_defined_vars());
$parsed = eval($input);
$vars = get_defined_vars();
foreach($defvars as $key) unset($vars[$key]);
$target = $vars;
foreach(explode(".", $syntax) as $key) {
if ($key == "\$") continue;
if (is_object($target) && isset($target->$key)) {
$target = $target->$key;
continue;
}
if (is_array($target) && array_key_exists($key, $target)) {
$target = $target[$key];
continue;
}
}
if (!is_scalar($target)) {
echo print_r($target, 1);
} else {
echo $target;
}
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment