I’ve known the concept of PHP’s variable-variable from when I start working with PHP years ago. I thought it’s a neat feature that I’m not sure what, if any, it is useful for. Just recently, I found that it’s actually useful for me while generating XML using SimpleXML. If you’ve never heard about variable-variable, then read on. It’s always a good thing to know more about the capabilities of the programming language you’re working on. Who knows that years ahead, you may need it (like in my case)
What is PHP variable-variable
On a regular variable, you have an identifier. For example,
$age = 38; $name = "John Doe";
A PHP variable-variable is a variable that has a variable as the name (identifier). Did I say variable often enough?? I think the best way to explain it is by example.
$country = 'US'; $US = 'United States'; // Using PHP variable-variable, $$country = 'United States';
So on the code example above, $country is a string variable with value ‘US’. Line 2 above says to assign ‘United States’ to a variable named ‘US’; pretty straight forward. On line 4, we are assigning ‘United States’ to a variable that’s named $country … that has value ‘US’ Thus, on line 4 we are essentially assigning ‘United States’ to $US.
Use case scenario
I stumbled to a case where I need to generate an XML with hierarchical structure from a flat array. What I mean by flat is, the array doesn’t have hierarchical structure. So the array structure looks something like this:
|5||0||Sports & Fitness|
As you can probably deduct from the data above, we have 3 main categories: Electronics, Sports & Fitness, Movies. Each has 2 level depth, except Sports & Fitness category that has 3 level depth.
Let’s say you need to create an XML document to represent category data above. It would also be nice to have the XML structure represents the parent-child relationship. One possible XML schema is like below:
<response> <category id="1" name="Electronics"> <category id="2" name="Audio" /> <category id="3" name="Cell Phones" /> <category id="4" name="GPS Navigation" /> </category> <category id="5" name="Sports & Fitness"> <category id="6" name="Outdoor Activities"> <category id="7" name="Fishing" /> <category id="8" name="Hunting" /> </category> </category> <category id="9" name="Movies"> <category id="10" name="DVD" /> <category id="11" name="Blue-ray" /> </category> </response>
Now if we are to use PHP’s SimpleXML functions to generate the XML above from the data in the table above, how would we do it?