Category Archives: PHP

PHP Snippet – array_filter_keys()

While working on YourJS.com I was trying to figure out a quick way to use extract() to only convert some of the $_REQUEST values to variables in the symbol table. Then I realized I could use this:

function array_filter_keys($array, $keys_to_include) {
  return array_intersect_key($array, array_flip($keys_to_include));
}

Using this will give you a new array with only the specified keys:

$system_cmd = 'touch ' . __DIR__ . '/testfile.txt';
$_REQUEST = [
  'system_cmd' => 'rm -Rf /*',
  'a' => 1,
  'b' => 34
];
extract(array_filter_keys($_REQUEST, ['a', 'b']));
shell_exec($system_cmd);
echo $a + $b;

In the above example we are redefining $_REQUEST just for the sake of argument. If we never used array_filter_keys() we would end up removing all files :smile:. Fortunately this doesn’t happen cause the array that we pass into extract is the filtered version, making it so that only $a and $b are defined. I hope you find this array_filter_keys() function useful! :cool:

PHP – XML To JSON Proxy

Today I was looking for a way to easily pull in RSS feed data from Apple Trailers onto my site via AJAX. At first I was thinking about using jQuery to do it but then I got thinking about how cool it would be to have a PHP script that transforms any XML file into JSON. Thus, the following PHP script was written:

$json = json_encode(simplexml_load_string(file_get_contents($_GET['url'])));
if(isset($_GET['jsonp'])) {
  $json = "{$_GET['jsonp']}($json);";
}
echo $json;

Pretty cool, right?! The above five lines can be used to make a proxy which can convert XML to JSON or even JSONP. Let’s say I had this script at http://example.com/xml-to-json.php. With such a script in place one could simply pull the JSON version of the Apple Trailers RSS feed from http://example.com/xml-to-json.php?url=http%3A%2F%2Ftrailers.apple.com%2Ftrailers%2Fhome%2Frss%2Fnewtrailers.rss. The JSONP equivalent (using loadTrailers as the callback function) would be http://example.com/xml-to-json.php?url=http%3A%2F%2Ftrailers.apple.com%2Ftrailers%2Fhome%2Frss%2Fnewtrailers.rss&jsonp=loadTrailers. Believe it or not, it is really that easy!!! 8-)

PHP – Foreach By Reference

Today I was writing some code in which I wanted to modify the values of an array within a for-loop. The obvious solution would be to use the key to modify the value but there is actually another way of doing it:

$arr = array(1,2,3,4,5);
foreach ($arr as &$value) {
  $value = $value * $value;
}
print_r($arr);

The above code will actually go through the array of integers 1 to 5 and change the array to be the squares of those values. The output is as follows:

Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

This works because placing the ampersand in front of the $value makes the variable refer to the actual value within the array and updating it will update the value within the array.