PHP unserialize serialized data - php

I have a problem with unserializing serialized data.
The data is serialized and saved in the database.
This data contains a uploaded .csv url that I want to give back to fgetcsv.
fgetcsv expects a array and now a string is given, so I need to unserialize the data but this gives me errors.
I found this online http://davidwalsh.name/php-serialize-unserialize-issues but this doesn't seem to work. So I hope somebody can tell me where I go wrong:
Here is the error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of 1 bytes in /xxx/public_html/multi-csv-upload.php on line 163
I found that this means that there are certain characters in the serialized data that makes the file corrupt after unserialization (",',:,;)
Line 163:
jj_readcsv(unserialize ($value[0]),true);` // this reads the url of the uploaded csv and tries to open it.
Here is the code that makes the data serialized:
update_post_meta($post_id, 'mcu_csv', serialize($mcu_csv));
This is WordPress
Here is the output of:
echo '<pre>';
print_r(unserialize($value));
echo '</pre>';
Array
(
[0] => http://www.domain.country/xxx/uploads/2014/09/test5.csv
)
The way I see it there shouldn't be anything wrong here.
Anybody some idea's how I can unserialize this so I can use it?
Here is what I did sofar...
public function render_meta_box_content($post)
{
// Add an nonce field so we can check for it later.
wp_nonce_field('mcu_inner_custom_box', 'mcu_inner_custom_box_nonce');
// Use get_post_meta to retrieve an existing value from the database.
$value = get_post_meta($post->ID, 'mcu_images', true);
echo '<pre>';
print_r(unserialize($value));
echo '</pre>';
ob_start();
jj_readcsv(unserialize ($value[0]),true);
$link = ob_get_contents();
ob_end_clean();
$editor_id = 'my_uploaded_csv';
wp_editor( $link, $editor_id );
$metabox_content = '<div id="mcu_images"></div><input type="button" onClick="addRow()" value="Voeg CSV toe" class="button" />';
echo $metabox_content;
$images = unserialize($value);
$script = "<script>
itemsCount= 0;";
if (!empty($images))
{
foreach ($images as $image)
{
$script.="addRow('{$image}');";
}
}
$script .="</script>";
echo $script;
}
function enqueue_scripts($hook)
{
if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
return;
wp_enqueue_script('mcu_script', plugin_dir_url(__FILE__) . 'mcu_script.js', array('jquery'));
}

You are attempting to access the first element of the serialized string:
jj_readcsv(unserialize ($value[0]),true);
As strings are essentially arrays of chars, you are trying to unserialize the 1st char of the serialized string.
You need to unserialize 1st then access the array element:
//php 5.4+
jj_readcsv(unserialize ($value)[0],true);
//php < 5.4
$unserialized = unserialize ($value);
jj_readcsv($unserialized[0],true);
Alternatively, if there is only ever one element, dont store an array in the 1st place, just save the url string, which doesnt need to be serialized:
//save
update_post_meta($post_id, 'mcu_csv', $mcu_csv[0]);
//access
jj_readcsv($value, true);

Related

Parsing part of a json object with multi levels using PHP

If you open the URL, you'll see that it's a very long string of sub objects. I want to extract the values for the 70 position. So far I've been able to extract the first tree without a problem ... But if you go deeper then I don’t get any feedback at all. Please check the code below and tell me, what am I doing wrong?
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port); // decode the JSON feed
echo $data[69]->port_name.'<br>';
echo $data[69]->port_status.'<br>';
echo $data[69]->passenger_vehicle_lanes->maximum_lanes.'<br>';
echo $data[69]->passenger_vehicle_lanes->standard_lanes->lanes_open.'<br>';
The following is working for me:
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port, true); // decode the JSON feed
echo "There are ".count($data)."Ports".PHP_EOL;
$found=false;
foreach ($data as $key => $value) {
//EDIT AFTER COMMENT**
if($value['port_number']==250401){
echo $value['port_name'].' '.$value['crossing_name'].PHP_EOL;
$found=true;
break;
}
}
if(!$found) echo "couldn't find port #";
can you try to change json_decode($port, true); (true will change object to array and it will be better to access it) like this and access it like in array echo $data[69]['passenger_vehicle_lanes']['maximum_lanes'].'<br>';

why is this php code not working?

This is the code I am using to scrape specific data from http://www.partyhousedecorations.com
however I keep getting this error (Fatal error: Call to a member function children() on a non-object in C:\wamp\www\webScraping\PartyHouseDecorations.php on line 8 )and I am stuck and can't seem to be able to fix it.
This is my code:
<?php
include_once("simple_html_dom.php");
$serv=$_GET['search'];
$url = 'http://www.partyhousedecorations.com/category-adult-birthday-party-themes'.$serv;
$output = file_get_html($url);
$arrOfStuff = $output->find('div[class=product-grid]', 0)->children();
foreach( $arrOfStuff as $item )
{
echo "Party House Decorations".'<br>';
echo $item->find('div[class=name]', 0)->find('a', 0)->innertext.'<br>';
echo '<img src="http://www.partyhousedecorations.com'.$item->find('div[class=image]', 0)->find('img', 0)->src.'"><br>';
echo str_replace('KWD', 'AED', $item->find('div[class=price]',0)->innertext.'<br>');
}
?>
Looks like $output->find('div[class=product-grid]', 0) doesn't return an object with a method called children(). Maybe it's returning null or something that's not an object. Put it in a separate variable and look what the value of that variable is.
$what_is_this = $output->find('div[class=product-grid]', 0);
var_dump($what_is_this)
Update:
I debugged your program, and apart from the simple html dom parser seemingly expecting classes to be given as 'div.product-grid' instead of 'div[class=x]' it also turns out that the webpage responds by returning a product list instead of a product grid. I've included a working copy below.
<?php
include_once("simple_html_dom.php");
$serv=$_GET['search'];
$url = 'http://www.partyhousedecorations.com/category-adult-birthday-party-themes';
$output = file_get_html($url);
$arrOfStuff = $output->find('div.product-list', 0)->children();
foreach( $arrOfStuff as $item )
{
echo "Party House Decorations".'<br>';
echo $item->find('div.name', 0)->find('a', 0)->innertext.'<br>';
echo '<img src="http://www.partyhousedecorations.com'.$item->find('div.image', 0)->find('img', 0)->src.'"><br>';
echo str_replace('KWD', 'AED', $item->find('div.price',0)->innertext.'<br>');
}
?>

can not echo a function content inside file_get_contents

Suppose this code prints Youtube:
<?php ytio_empt(); ?>
I want a dynamic way to echo the content of the above function in the place of 'YouTube' in the following xml data:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. 'YouTube' );
I have tried:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. ytio_empt() );
But in vain, the file_get_contents() always fails to open stream.
P.S: Perhaps using HTML will work: to put <?php ytio_empt(); ?> in the place of ytio_empt() in $xmlData. I just don't know how to end PHP function and resume it later..
So as you posted your function in the comments:
function ytio_empt() {
if(empty(get_option('ytio_username'))) {
echo esc_attr( get_option('ytio_id') );
//^^^^
} else {
echo esc_attr( get_option('ytio_username') );
//^^^^
}
}
You will see you don't return the values you just print them! So in order to return them you simply have to change echo -> return.
And if you want to read more about return values see the manual: http://php.net/manual/en/functions.returning-values.php

Save a array to MySQL

I got this API Moves PHP Script up and running, but i can't seem to figure out how to save the array to a MySQL db? How do i do that? I want to save the information, but also print the information on the page like i do now?
I use the script from this git .. https://github.com/borivojevic/moves-api-php
$Moves = new \Moves\Moves($access_token);
$data = $Moves->dailySummary(array('pastDays' => 1));
foreach($data as $dag)
{
echo 'Dato: <b>', $dag['date'], '</b> <br />';
foreach($dag['summary'] as $aktivitet)
{
if($aktivitet['activity'] == 'walking')
{
$daglig_procent = ($aktivitet['steps']/10000 * 100);
echo 'Antal skridt: <i>', $aktivitet['steps'], '</i>';
echo '<br />';
echo 'Procent: <i>', round($daglig_procent), ' % </i>';
}
}
echo '<hr />';
}
}
If you want to save an array to a db, json_encode it and save the json string in a text/varchar field; json_decode it to get the array back from the db data.
You can use these function
serialize
or
json_encode
This this an example:
$mydata=Array("some"=>Array("fhdlslfd"=>"gklhml", "giuolmmlh"), "gfukilfkgl");
You can simply use serialize($mydata); for add in bdd and unserialize($resultatsql); for use the vars from bdd

Formatting XML in to JSON with PHP

I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));

Categories