Strange behavior on json_decode in PHP code - php

I was just studying and messing around with PHP, when i encountered something that, to me, doesn't make much sense, but i could be missing something.
So, i have this spreadsheet file that i load on my system, and i want to print every data that is inside the file. I load the file, and turn it into an array, like this:
$file = $request->spreadsheet;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
$spreadsheet = $spreadsheet->getActiveSheet();
$data_array = $spreadsheet->toArray();
So far so good. Now, i want to print everything that is inside this file, but i wanted to display is using it's attributes, something like:
foreach($data_array as $data){
$x = json_decode($data[2]);
echo $x->nome;
echo $x->telefone;
}
I'm accessing $data[2] because its the third position of the array that contains all the info about the user, like name, telephone or whatever.
The thing is, if i run the code like i've just showed, i get the error "Trying to get property 'nome' of non-object", but if i try to echo the EXACT same thing, but outside the "foreach", like this:
foreach($data_array as $data){
$x = json_decode($data[2]);
}
echo $x->nome;
echo $x->telefone;
I have no error at all, and shows me the info perfectly, so.. what is going on ? lol

The property of a non-object error inside the foreach means this particular row either has no JSON or is invalid JSON. Your last snippet working OK means the last row has valid JSON.
It's possible the first row is column header, for example "Data" which of course will not parse as JSON and will trigger the error.
Look at your spreadsheet rows to narrow it down, and you can output var_dump($data[2]) in the foreach.

Related

Retrieve string from json

I'm trying to retrieve a URL string from some json code.
Here is the json code
{"files":["www.example1.com"],"previews":["www.example1preview.com"],"meta":{},"userId":"guest","product":{"id":"2335","name":"standard"},"type":"u"}
Looking at what I've seen in the PHP manual I'm trying to retrieve previews like this.
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->{'previews'};
?>
This doesn't seem to output the value however.
By experimenting with php -a command on terminal, I've put your json into json_decode and managed to get your link by just doing:
print $meta_value_json->previews[0];
The only reason to use print $meta_value_json->{'previews'}; at least according to php documentation is if you want an object as output and the key trying to retrieve is numerical or of a type that is not supported by php.
By experimenting a bit further, the reason that print $meta_value_json->{'previews'}; fails is because print expects a string, in our case here previews is an array. Therefore if you do print $meta_value_json->{'previews'}[0]; it will also work as expected.
You need to get the value from your decoded json like this: $class->parameter.
Knowing that previews is an array, you will also need to choose a specific element from it to print ( I got the first one ):
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->previews[0]; /// get the specific value
?>

echoing variable works, but not putting inside a file?

I have a variable called $filter. If I run echo $filter; I get the contents of it. However, If I run
file_put_contents("/nrj/vvr/tmp/lol", $filter);
I do get the file, but the contents is just 1. It should contain alot of different things. I use the exact same syntax usually, and it works. I get no error messages.
This line was the problem
$filter = curl_exec($ch);
For some reason, it ignores the first things and just executes it without setting any variable. Under this I had
echo $filter;
Giving me the impression that it was that line that output it, but it was the one above.

SimplePie RSS not accepting variable with comma separated strings

I'm trying to use SimplePies "$feed->set_feed_url (array());" function but I am having major difficulty understanding why it wont accept my values.
When I add the URLS manually (i.e directly below), they work just fine. The feeds go through ok and displays the feeds as needed.
$feed ->set_feed_url (array(
'http://www.theverge.com/tag/rss',
'http://feeds.ign.com/ign/all'
));
I have URLS in a database table that I am pulling out like normal with a while loop. I then append a comma and remove the trailing comma so its nice for the SimplePie array. Like so:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb .= $row[0] . ",";
}
$result4mdb = substr($result4mdb, 0, strlen($result4mdb) -1);
echo "the result is: " . $result4mdb;
When I do this, and echo out "$result4mdb", it prints out: the result is: http://www.gamespot.com/feeds/mashup/,http://www.theverge.com/tag/rss
Meaning that the variable is good and printing out what i need. So far so good.
I then go into the simplePie code, put in my varialble like so:
$feed ->set_feed_url (array($result4mdb));
and nothing happens. I don't get any errors or anything, just that the page stays blank and nothing comes up.
For testing, I do a gettype($result4mdb); and it tells me that the variable is a "string" and again, the output of this variable when echoed is the URLS it got from the database so I KNOW that the whole process so far is working.
For further testing, I go to the database and remove one of the URLS so that when queried, that it returns one value, and all of the sudden SimplePie works.
I've been searching for a good day and a half now, trying different things and googling as much as possible but to no avail. I just cant quite get it.
I'm at my wits end. Any assistance as to why this isn't working is GREATLY appreciated.
Thank you in advance everyone
You're just producing a string containing comma seperated values. What you need is an array, so just explode() your string:
Change:
$feed ->set_feed_url (array($result4mdb));
to
$feed ->set_feed_url (explode(',', $result4mdb));
More elegant version, change:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb .= $row[0] . ",";
}
to
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb[] = $row[0];
}
This way you're not creating a string that needs to be exploeded, but create an array at first.

Simple use PHP to get data from XML

I am getting some variable where is XML file, I can't edit it or do anything with it.
So what I do:
$xml = $client->get_details('WF0GXXGBBG7P857BB');
$xml = simplexml_load_string($xml);
//print_r($xml);
$vin = $xml->vin;
print_r($vin);
If I uncomment print_r($xml) it just prints out whole xml and works cool (output is http://pastebin.com/w5VVysZU), but if I use second part with print_r($vin) it just displays just SimpleXMLElement Object ( ),
Any idea what can I do? How can I fix this? I've tried like 20 tutorials and always get no output or error with using nonobject something.
EDIT 1:
I need it to display one specific thing from this XML, in example it's VIN, so from this big amount I want script to find where is [vin] => WF0GXXGBBG7P857BB and echo WF0GXXGBBG7P857BB
EDIT 2:
My XML: http://pastebin.com/1KLB5Ba0
SimpleXML elements can and have to be type casted to strings if you want to display them that way. Otherwise, as you seen, it just tells you that it is an object.
$vin = (string) $xml->vin;
// OR
print_r((string) $vin);

json_encode won't escape newlines

Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.

Categories