I am a junior programmer. Recently I've been trying to develop in PHP. I am trying to create a basic page about countries. For some reason I cannot grab the information from this API page. Can anyone give me some tips?
Here is what a sample country array looks like. Ideally I would like to try to grab the "name" attribute.
Here is my HTML and PHP:
<?php
if(!empty($_GET['country'])) {
$country_url = 'https://restcountries.eu/rest/v1/name/' . urlencode($_GET['country']) . '?fullText=true';
$country_json = file_get_contents($country_url);
$country_array = json_decode($country_url, true);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8" />
<title> PHP Country Practice </title>
</head>
<body>
<form action="">
<input type = "text" name = "country" />
<button type="submit">submit </button>
</form>
<?php
if(!empty($country_array)) {
echo '<p> $country_array['name'] </p>';
}
?>
</body>
</html>
You're returning an associative array, so use identifiers like this:
$country_array[0]['name']
If it is object use the below code.
echo $country_array[0]->name;
For array use
echo $country_array[0]['name'];
You need to access the correct array index, in this case 0.
Variables don't expand inside single-quotes, you need to use
double-quotes and surround it with brackets {} (tks AbraCadaver), i.e.:
echo "<p> {$country_array[0]['name']} </p>";
Related
I have a php form that users submit their start / end dates. The form then needs to pull the results from .xml hosted on a different URL. The URL varies based on the dates entered by the user - dates become part of the URL as you can see below.
So, simply put... The user enters the dates. It calls the xml file via the URL (which changes slightly as the dates are entered into that URL) and it displays the results on a new page.
I would rather do it via PHP than AJAX if possible.
This is the frontend of my form:
<html>
<body>
<form action="test_get.php" method="get">
Start Date: <input type="text" id="start" name="start"><br>
End Date: <input type="text" id="end" name="end"> <br>
<input type="submit">
</form>
</body>
</html>
This is 'test_get.php':
<html>
<body>
<form onSubmit="return process();">
Start Date: <?php echo $_GET["start"]; ?><br>
End Date: <?php echo $_GET["end"]; ?>
</form>
</body>
<script>
function process()
{
var url="http://99.999.999.999:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug," + document.getElementById("start").value + "," + document.getElementById("end").value;
location.href=url;
return false;
}
</script>
</html>
But it doesn't work. I also tried this:
<html>
<body>
<?php
$xml=simplexml_load_file("http://99.999.999.999:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug," + document.getElementById("start").value + "," + document.getElementById("end").value"); or die("Error: Cannot create object");
echo $xml->field . "<br>";
echo $xml->data . "<br>";
?>
</body>
</html>
But again, no luck. Can anyone see what i'm missing?
I can also share what my .xml form looks like if needed. Any help is greatly appreciated - i've been tackling this for days! Thanks! :)
UPDATE: This is my updated code for test_get.php:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<?php
$url = '"http://69.239.118.197:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug,'.$_GET['start'].','.$_GET['end'].'"';
$xml = simplexml_load_file($url);
echo $xml->field . "<br>";
echo $xml->data . "<br>";
echo var_dump($xml). "<br />";
?>
</body>
</html>
In the last block of code that you posted, you are using JavaScript outside of script tags, so this is definitely not going to work. Have you tried instead putting your $_GET variable into the query string?
Note* I pulled out the query string for more readability. It's hard for me to verify that this is working for you outside of your environment, but give it a shot.
You've got this:
$xml=simplexml_load_file("http://99.999.999.999:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug," + document.getElementById("start").value + "," + document.getElementById("end").value"); or die("Error: Cannot create object");
I'm recommending this:
$url = '"http://99.999.999.999:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug,'.$_GET['start'].','.$_GET['end'].'"';
$xml = simplexml_load_file($url);
*************EDIT*****************
So, after attempting to manipulate the data that simplexml_load_file returns I decided to try file_get_contents. The solution below returns the data value from the xml file in string format.
$_GET['start'] = '08/30/2017';
$_GET['end'] = '08/31/2017';
$xml = file_get_contents("http://69.239.118.197:81/fmi/xml/fmresultset.xml?-db=Front_Desk&-lay=WebRoomQuery&-findany&-script=WebQueryPSOS&-script.param=snug,".$_GET['start'].','.$_GET['end'].'"');
echo $xml;
I am new to programming and would like to begin adding more advanced applications to my site. I am trying to call an api with php. I'm having trouble getting it to return json format.
<?php
if(!empty($_GET['hospital_name'])) {
$Hospcomp_url = 'https://data.medicare.gov/resource/rbry-mqwu.json?hospital_name=' . urlencode($_GET['hospital_name']);
$Hospcomp_json = file_get_contents($Hospcomp_url);
json_decode($Hospcomp_json, true);
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CMS</title>
</head>
<body>
<form action="">
<input type="text" name="hospital_name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
It seems, you get your result properly but you don't do anything with it. First of all, you don't assign the array decoded from JSON to a variable. And then, you don't echo or process your array otherwise.
Please replace this:
json_decode($Hospcomp_json, true);
with something like this:
$decoded = json_decode($Hospcomp_json, true);
var_export($decoded);
Then you'll have your output and you will be able to decide what to do next.
Calls are correct, just var_export it.
if(!empty($_GET['hospital_name'])) {
$Hospcomp_url = 'https://data.medicare.gov/resource/rbry-mqwu.json?hospital_name=' . urlencode($_GET['hospital_name']);
$Hospcomp_json = file_get_contents($Hospcomp_url);
var_export(json_decode($Hospcomp_json, true));
}
I am trying to enter a PHP 2D array variable as the value-attribute of a text input form in HTML.
Here is what I'm trying to do:
<?php
$test = array(array());
$test[0][0] = 123;
echo <<<_END
<html>
<head>
<body>
<form action = "test.php">
<input type = "text" value = "$test[0][0]">
</form>
<body>
<head>
<html>
_END;
?>
I get a warning saying: Notice: Array to string conversion in "path" on line 12,
and the form just displays Array[0].
What is happening here? How should this be done to get correct results?
Surround your variable with curly braces. So:
echo <<<_END
<html>
<head>
<body>
<form action = "test.php">
<input type = "text" value = "{$test[0][0]}">
</form>
<body>
<head>
<html>
_END;
It is best practice to surround your variables used inside of a string with curly braces. Especially array variables. This tells php that the variable name is everything between the curly braces.
I am writing a PHP code in Adobe Dreamweaver. My code is as shown below. I am expecting my code to output two boxes, into which I write something. And when I click on the submit button, I expect to see the two separate things that I entered into the box to be concatenated. But I'm not getting a concatenation. In fact, NOTHING happens when I click on submit. I am confused. Is this code not something I should be using Dreamweaver for? I am relatively new to PHP and I do not understand all the bits. My suspicion is that Dreamweaver does not recognize "twoFieldForm.php". Can someone please tell me how I can overcome this issue?
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1>Form Filler</h1>
<?php
function joined($s1, $s2) {
return array($s1.$s2, strlen($s1.$s2));
}
$first = $_GET[fieldOne];
$second = $_GET[fieldTwo];
$answer = joined($first, $second);
echo "The concatenated string is \"{$answer[0]}\"
and its length is \"{$answer[1]}\";
?>
<form action = "twoFieldForm.php" method = "get">
Field 1 : <input type = "text" name = "fieldOne"/>
Field 2 : <input type = "text" name = "fieldTwo"/>
<input type = "submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1>Form Filler</h1>
<?php
function joined($s1, $s2) {
return array($s1.$s2, strlen($s1.$s2));
}
$first = $_GET['fieldOne'];
$second = $_GET['fieldTwo'];
$answer = joined($first, $second);
echo "The concatenated string is \"{$answer[0]}\"
and its length is \"{$answer[1]}\"";
?>
<form action="" method="GET">
Field 1 : <input type="text" name="fieldOne"/>
Field 2 : <input type="text" name="fieldTwo"/>
<input type="submit">
</form>
</body>
</html>
Explanation: You have to add quotes in $_GET['']. Remember indention please, always when I see people using adobe dreamweaver, their code is horrible... If you are refering to the same file, you don't have to use an action="somewhat.php". Just leave it empty. Aswell you have missed a " after your echo statement.
This will work now. Please start using a good IDE then you won't have those basic mistakes because the IDE will show you your mistakes already...
Try add quotes:
$first = $_GET['fieldOne'];
$second = $_GET['fieldTwo'];
$answer=$_GET['fieldOne'].$_GET['fieldTwo'];
echo "concatenated string is:".$answer;
try this...
I came across someone asking the question,
How can I pass a variable up the page (on the same page?).
I had a think about it but couldn't think of how to do it myself, so I was wondering if it is even possible?
So what he was trying to do was change the value of $a at the top of the page at the same time as the bottom value of $a.
Is it possible? If so how?
Thanks in advanced.
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $testf;
echo( "Bottom " . $a);
}
?>
</body></html>
Edit:
After seeing answers, maybe it can be done with jquery, ajax or javascript?
No, you'll need to move the if statement to the top, and any variables you calculate that need to be in the if statement also to the top.
Something like:
<?php
if ("submit" == $submit) {
$a = $testf;
}
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
echo( "Bottom " . $a);
?>
</body></html>
It's considered a good practice to have all the logic before you start outputting the HTML anyways. Your HTML should ideally have as less logic as possible.
More info: https://stackoverflow.com/a/95027/320615 and https://stackoverflow.com/a/1088791/320615
You can probably bend over backwards to make that work somehow.
But the real answer is to handle all your business logic before you start outputting any HTML. You need to decide at the beginning of your code whether the current request is a form submission or not and set variables and HTML templates accordingly. Never mix business logic into the middle of your HTML templates.
You have to use the $_POST['testf'] and $_POST['submit'] variable.
And also check if it exists with isset : php manual isset
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $_POST['testf'];
echo( "Bottom " . $a);
}
?>
</body></html>
You can't do it in PHP, but you can't change HTML once it's fully loaded using javascript (and jquery to make it easier).
EDIT : ok I read your code a bit quickly the first time :
I don't understand the echo before the <html> tag, doesn't seem right. Also you want to give the value of a POST var to $a, so just :
if(isset($_POST['testf'])) {
echo $_POST['testf'];
}