Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBjörn Norén
9,569 PointsTurn document.txt into a Array? PHP
Hi, I have created this easy page where you can put in content into a box: http://studenter.miun.se/~bjno1501/dt057g/webbutveckling2/php/practise/project/project.php
.. and the information is saved into a text-file named document.txt. Right now, if you look at that file, it looks like this: s:4:"fhfh";s:3:"lkn";s:3:"lkn";s:5:"bhvhv";s:5:"nknkn";s:3:"jkh";s:3:"lkn";s:6:"iugiug";s:4:"dgnf";s:3:"dfh";s:5:"sdsds";s:9:"fgmfmgfgm";s:4:"sfsf";s:4:"jnjn";s:3:"kjn";
My question is: how do unserialize this so I can echo all of the information? Because when I now unserialize this and then echos is, I get: "fhfh", which is the first part of the information. Am I supposed to turn it into a Array?
Any help is very much appretiated! Thank you!
2 Answers
Codin - Codesmite
8,600 Points<?php
$arr = unserialize(/* Your serialized content or variable here */);
var_dump($arr);
?>
By saving the result of your unserialize to an array you will be able to loop through the contents :)
<?php
$arr = unserialize(/* Your serialized content or variable here */);
foreach($arr as $x){
echo $x . '<br>';
}
?>
Björn Norén
9,569 PointsThis is how the code looks like:
<?php
$file = "./document.txt";
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
$ser = serialize($name);
file_put_contents($file, $ser, FILE_APPEND | LOCK_EX);
$document = file_get_contents($file);
$unser_document = unserialize($document);
foreach($unser_document as $x){
echo $x . '<br>';
}
}
}
?>
</body>
</html>
Codin - Codesmite
8,600 PointsRemove the foreach array and try:
var_dump($unser_document);
This is just to dump the contents of $unser_documnet to make sure it is an array and contains your content as the error you are recieiving is normally caused by foreach looping something that is not an array.
Björn Norén
9,569 PointsBjörn Norén
9,569 PointsHi, I have tried to use foreach, but I get this error: "Invalid argument supplied for foreach()"
Do you hknow what could be wrong? Thank you for reaching out!