Newbie PHP: Insert a variable for echoing - php

I'd like to be able to echo $domain from this
$domain = $response['results']['$MYVAR']['shortUrl'];
I've tried curly braces and various other ways of formatting $MYVAR but the syntax is wrong.
Help most welcome !
EDIT --> var_dump($response):
object(stdClass)#1 (4) {
["errorCode"]=> int(0)
["errorMessage"]=> string(0) ""
["results"]=> object(stdClass)#2 (1) {
["http://www.domain.com"]=> object(stdClass)#3 (5) {
["userHash"]=> string(6) "oSEMki"
["shortKeywordUrl"]=> string(0) ""
["hash"]=> string(6) "oms2ZB"
["shortCNAMEUrl"]=> string(20) "http://bit.ly/LALALA"
["shortUrl"]=> string(20) "http://bit.ly/LALALA"
}
}
["statusCode"]=> string(2) "OK"
}
I can see the "domain.com" element fine but when I do this:
var_dump($response['results'][$MYVAR]);
it returns NULL ! Which must be why $domain = $response['results'][$MYVAR]['shortUrl']; fails too. Odd !
--EDIT 2 --
var_dump($MYVAR); gives:
string(118) "http://www.domain.com"

Try this:
$domain = $response['results'][$MYVAR]['shortUrl'];
echo $domain;
Are you sure it's stored in a 3 dimentional array like that?
Because that looks like needless complication.

Try it without quotes
$domain = $response['results'][$MYVAR]['shortUrl'];
or use double quotes
$domain = $response['results']["$MYVAR"]['shortUrl'];
EDIT:
In reaction to your edit. You are accessing variable like an associative array but the variable is instance of stdObject. So if you want to acces it, you must retype it like this:
$tmp = (array) $response;
$domain = $tmp['results'][$MYVAR]['shortUrl'];
or access it like object
$domain = $tmp->results->$MYWAR->shortUrl;
EDIT 2:
So it is strange, because http://www.domain.com is not 118 characters long, as var_dump wrote.
Where and how did you filled up the variable $MYVAR?

$domain = $response['results'][$MYVAR]['shortUrl'];
You don't need quotes around $MYVAR.

Have you tried without the quotes around $MYVAR?

It's an object.
$domain = $response->results->$MYVAR->shortUrl;

Related

Store json data to php variable

im trying to store data from a json file to php variables. But it wont work when i try to echo the variable for later use.
This is my json file:
"[{\"channelId\":150342342,\"channelName\":\"example.no\",\"channelUrl\":\"http:\/\/www.example.no\"},{\"channelId\":1529564329,\"channelName\":\"example2.no\",\"channelUrl\":\"http:\/\/www.example2.no\"},{\"channelId\":1536534822,\"channelName\":\"example3.no\",\"channelUrl\":\"http:\/\/www.example3.no\"}]"
This is my code:
<?php
require_once('config.php');
$channeljson = file_get_contents('channels.json');
$data = json_decode($channeljson, true);
$channelid = $data['channelId'];
$channelname = $data['channelName'];
$channelurl = $data['channelUrl'];
I have tried many other ways too..
Anyone have any tips that could work?
Your file contains a json that represents a string, since it starts and finishes with the " character. Another issue are the escape characters \.
If you don't want to change de routine that writes the json files, you can solve your problem by correcting the invalid json:
$data = json_decode(trim(stripslashes($channeljson), '"'), true); // Removes the escape and the enclosing " characters
There is one more problem: the json represents an array of objects (arrays since you are passing true to the second json_decode function) and you are trying to access $data like a regular array.
See the $data contents:
array(3) {
[0]=>
array(3) {
["channelId"]=>
int(150342342)
["channelName"]=>
string(10) "example.no"
["channelUrl"]=>
string(21) "http://www.example.no"
}
[1]=>
array(3) {
["channelId"]=>
int(1529564329)
["channelName"]=>
string(11) "example2.no"
["channelUrl"]=>
string(22) "http://www.example2.no"
}
[2]=>
array(3) {
["channelId"]=>
int(1536534822)
["channelName"]=>
string(11) "example3.no"
["channelUrl"]=>
string(22) "http://www.example3.no"
}
}

PHP - Variable returns NULL when setting in if statement

I'm somewhat of an amateur php programmer and am looking for help with an if statement that is not working as I intend it to.
<?php
var_dump($_GET['name']);
var_dump($_GET['id']);
var_dump($search);
var_dump($param);
var_dump($raw);
var_dump($json);
// for debugging
error_reporting(E_ALL);
ini_set('display_errors', 'on');
// choose between either the name or id parameter
if(isset($_GET['name'])) {
$search = $_GET['name'];
}
elseif(isset($_GET['id'])) {
$search = $_GET['id'];
}
// build parameters for either name OR id
if (isset($_GET['name'])) {
$param = http_build_query(array(
'name' => $_GET['name'],
'getMembers' => 'yes',
'rand' => rand(),
));
}
elseif (isset($_GET['id'])) {
$param = http_build_query(array(
'id' => $_GET['id'],
'getMembers' => 'yes',
'rand' => rand(),
));
}
// get raw json from server
$raw = file_get_contents("https://example.com/file.php?".$param);
// decode the raw json response
$json = json_decode($raw);
... ?>
Notice how I've dumped the vars on the third line for debugging purposes. $search, $param, $raw, and $json all return NULL every time. I'm thinking it has something to do with the if statements, but I can't figure out what for the life of me. Help would be much appreciated. Cheers!
EDIT:
Okay! We're getting somewhere! I moved var_dump($json); farther down the page and got this jumble as a result:
object(stdClass)#2 (2) { ["guild"]=> object(stdClass)#1 (11) { ["guild_id"]=> string(3) "182" ["guild_name"]=> string(7) "Jiggmin" ["creation_date"]=> string(19) "2013-05-07 10:32:02" ["active_date"]=> string(19) "2013-05-07 10:32:02" ["member_count"]=> string(1) "1" ["emblem"]=> string(18) "default-emblem.jpg" ["gp_total"]=> string(1) "0" ["gp_today"]=> string(1) "0" ["owner_id"]=> string(7) "1939717" ["note"]=> string(13) "Hehe, trolls." ["active_count"]=> string(1) "0" } ["members"]=> array(1) { [0]=> object(stdClass)#3 (6) { ["user_id"]=> string(7) "1939717" ["name"]=> string(11) "snuppaper97" ["power"]=> string(1) "1" ["rank"]=> string(2) "23" ["gp_today"]=> NULL ["gp_total"]=> NULL } } }
I then tried to do echo $json; on line 58 and got this monstrosity:
**Recoverable fatal error:** Object of class std class could not be converted to string in /Path/To/File.php on line 58
First of all, do not use globals, they are a very old and bad way of coding in php.
instead of isset($_GET['name']) use array_key_exists('name', $_GET) as isset($_GET['name']) returns false if it is set to NULL, if you don't want null either explicitly add null !== $_GET['name'] as well, that way you know exactly what the code is doing.
there seems to be no default for your parameters, eg, if none of them are ever set, there will be no new parameter string build
Can you provide us with a sample url and the code where you build the url ? or where you use $param
They are at the top of the script, so these vars haven't been defined!
var_dump($search);
var_dump($param);
var_dump($raw);
var_dump($json);
They were always going to be null until you set them as something! Where are the vars supposed to come from? Move the var_dumps below and you'll probably start seeing stuff :-)
EDIT: Now you have an object of stdClass. To json encode that, we must convert it to an array! It's as easy as:
$array = (array) $object;
$json = json_encode($array);

Get Value from URL - GET Request

Hello I'm trying to get specific values out of my url that looks like this:
http://test.com/search.php?go&s=20&cacheKey=-5d36c171:14b930086c4:-561&cacheLocation=10.186.170.204:7300&customerSessionId=0ABAAACC-36C1-7191-4B92-30086C490817
What I have tried is e.g this:
$url .= '&cacheKey=' . strval($_GET['$cacheKey']);
But the value is not parsed correctly - What am I doing wrong ?
When I var_dump the $_GET I get the array out with all the values:
array(5) { ["go"]=> string(0) "" ["s"]=> string(2) "20" ["cacheKey"]=> string(26) "-5d36c171:14b930086c4:-561" ["cacheLocation"]=> string(19) "10.186.170.204:7300" ["customerSessionId"]=> string(36) "0ABAAACC-36C1-7191-4B92-30086C490817" }
Try using:
$url .= '&cacheKey=' . strval($_GET['cacheKey']);
Note the missing $ in the array index.
Remove $ from CacheKey.
$CacheKey is different from CacheKey.

Selecting item from multi-dimensional array

I have an array with the following contents:
$tester
array(1) {
[0]=>
object(CategoryItem)#79 (17) {
["type"]=>
string(0) ""
["addedInVersion"]=>
string(4) "0.02"
["lastUpdatedInVersion"]=>
string(4) "0.02"
["AToZ"]=>
bool(false)
["name"]=>
string(22) "Page Name"
["scopeNotes"]=>
string(0) ""
["historyNotes"]=>
string(13) "Added in 0.02"
["broaderItems"]=>
array(0) {
}
I want to echo out the name, if this case Page Name and then use this in an if statement.
I have but this errors, I also tried $tester->CategoryItem->name but no joy.
Is there anything obvious I am missing?
You need to access it like this:
$name = $tester[0]->name;
echo $name;
you have some leaks in your php OOP understanding, you should fix them by following some tutorials like these ones:
http://www.killerphp.com/tutorials/object-oriented-php/
http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762
http://www.tutorialspoint.com/php/php_object_oriented.htm
Now to answer your question, your code should be this:
$the_name = $tester[0]->name;
if($the_name == 'whatever value you want') {
echo $the_name;
}
first of all, your initial variable is a array, therefor, $tester[0], then, this position is an object of the class CategoryItem so you use scope: $tester[0]->value
As for the last of your values in the class properties, broaderItems, this is again an array, so to access one of his values, you will have to call it like:
$tester[0]->broaderItems[0]; //or whatever the keys you will have here
Hope this helps!
:D

Why can't I get PHP to show me a single json element

Man this JSON thing is chewing away at my day. Is it suppose to be this difficult? Probably not. Ok, so I am receiving a URL with a json data set in it.
It looks like this:
jsonval={%22Fname%22:+%22kjhjhkjhk%22,+%22Lname%22:+%22ghghfhg%22,+%22conf[]%22:+[%22ConfB%22,+%22ConfA2%22],+%22quote%22:+%22meat%22,+%22education%22:+%22person%22,+%22edu%22:+%22welding%22,+%22Fname2%22:+%22%22,+%22Lname2%22:+%22%22,+%22gender%22:+%22B2%22,+%22quote2%22:+%22Enter+your+meal+preference%22,+%22education2%22:+%22person2%22,+%22edu2%22:+%22weld2%22,+%22jsonval%22:+%22%22}
And when I run json_decode in PHP on it, it looks like this:
object(stdClass)#1 (13) { ["Fname"]=> string(9) "kjhjhkjhk" ["Lname"]=> string(7) "ghghfhg" ["conf[]"]=> array(2) { [0]=> string(5) "ConfB" [1]=> string(6) "ConfA2" } ["quote"]=> string(4) "meat" ["education"]=> string(6) "person" ["edu"]=> string(7) "welding" ["Fname2"]=> string(0) "" ["Lname2"]=> string(0) "" ["gender"]=> string(2) "B2" ["quote2"]=> string(26) "Enter your meal preference" ["education2"]=> string(7) "person2" ["edu2"]=> string(5) "weld2" ["jsonval"]=> string(0) "" }
I guess I should mention it was encoded as a serialized object from the form page and then encoded and sent over...Don't know if that will make a difference.
Anyway, I dutifully check the PHP manual, and everything, as always, looks simple enough to implement. And then, of course, I try it just the way they tell me and I miss something that's probably obvious to everyone here but me. This bit of code, returns nothing except my text that I'm echoing:
<?php
$json = $_GET['jsonval'];
$obj = var_dump(json_decode($json));
echo "<br><br>ELEMENT PLEASE!" . $obj;
print $obj->{"Fname"}; // 12345
?>
I mean, all I want is to see the values of my individual key/values and print them out. What have I done wrong here?
Thanks for any advice.
This line is completely wrong:
$obj = var_dump(json_decode($json));
var_dump() returns nothing
You need:
$obj = json_decode($json);
Turn display_errors on in your php.ini and set up ERROR_REPORTING = E_ALL. And continue developing with such settings.
You put this:
print $obj->{"Fname"}; // 12345
It should be
print $obj->Fname; // 12345
I think you are not calling out data from the object incorrectly.
Needs to be something like:
$data = (json_decode(urldecode('{%22Fname%22:+%22kjhjhkjhk%22,+%22Lname%22:+%22ghghfhg%22,+%22conf[]%22:+[%22ConfB%22,+%22ConfA2%22],+%22quote%22:+%22meat%22,+%22education%22:+%22person%22,+%22edu%22:+%22welding%22,+%22Fname2%22:+%22%22,+%22Lname2%22:+%22%22,+%22gender%22:+%22B2%22,+%22quote2%22:+%22Enter+your+meal+preference%22,+%22education2%22:+%22person2%22,+%22edu2%22:+%22weld2%22,+%22jsonval%22:+%22%22}')));
echo $data->Fname;

Categories