I am having some trouble pulling the volume name in the Tags section using the Amazon PHP SDK.
I'm able to print the Volume ID but since the Tags are in a separate array, I am not sure how to reference the value of the Key called 'Name'.
$east_client = \Aws\Ec2\Ec2Client::factory($east_config);
$east_result = $east_client->describeVolumes();
$east_volumes = $east_result['Volumes'];
foreach ($east_volumes as $e)
{
echo $e['VolumeId'] . "\n";
}
Here are the API docs for describeVolumes() in case you haven't seen them: http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.Ec2.Ec2Client.html#_describeVolumes.
Try something like this:
foreach ($volumes as $volume) {
echo "{$volume['VolumeId']}\n";
foreach ($volume['Tags'] as $tag) {
echo "- {$tag['Key']}: {$tag['Value']}\n";
}
echo "\n";
}
Related
I've written some code in php to scrape some preferable links out of the main page of wikipedia. When I execute my script, the links are coming through accordingly.
However, at this point I've defined two functions within my script in order to learn how to pass links from one function to another. Now, my goal is to print the links in the latter function but it only prints the first link and nothing else.
If I use only this function fetch_wiki_links(), I can get several links but when i try to print the same within get_links_in_ano_func() then it prints the first link only.
How can I get them all even when I use the second function?
This is what I've written so far:
include("simple_html_dom.php");
$prefix = "https://en.wikipedia.org";
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links = $prefix . $links;
return $absolute_links;
}
}
function get_links_in_ano_func($absolute_links)
{
echo $absolute_links;
}
$items = fetch_wiki_links($prefix);
get_links_in_ano_func($items);
Your function returned the value at the very first iteration. You will need something like this:
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
$absolute_links = array();
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links []= $prefix . $links;
}
return implode("\n", $absolute_links);
}
I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU¤cyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}
I have this php code to check whether an image exists or not.
foreach($pic_switch as $pic_switch_key => $pic_switch_value)
{
if ($pic_switch_value == "no-image")
{
$img_url = 'http://www.reuters.com/resources_v2/images/masthead-logo.gif';
}
else
{
$img_url = $img_location . $pic_switch_key . '.jpg';
}
}
The above code works great.
I would like to echo $img_url outside the foreach. I tried:
echo '<pre>'.print_r($img_url,true).'</pre>';
but it only gives the URL of the last image. I would like to display the URL of all the images. I would like to display all of them outside the Foreach, rather than echo the URL inside it.
When you use foreach this way, you will end up storing the last variable only in the $img_url. So use this way:
foreach ($pic_switch as $pic_switch_key => $pic_switch_value)
{
if ($pic_switch_value == "no-image")
{
$img_url = 'http://www.reuters.com/resources_v2/images/masthead-logo.gif';
}
else
{
$img_url = $img_location . $pic_switch_key . '.jpg';
}
echo '<pre>' . print_r($img_url, true) . '</pre>';
}
I don't understand why you can't echo from within a loop but one method would be to build a string within the loop and echo it later in the script.
It would be neater to build an array of the URLs and echo from within a for loop later.
I'm creating a "Madlibs" page where visitors can create funny story things online. The original files are in XML format with the blanks enclosed in XML tags
(Such as blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb> ).
The form data is created using XSL and the results are saved using a $_POST array. How do I post the $_POST array between the matching XML tags and then display the result to the page? I'm sure it uses a "foreach" statement, but I'm just not familiar enough with PHP to figure out what functions to use. Any help would be great.
Thanks,
E
I'm not sure if I understood your problem quite well, but I think this might help:
// mocking some $_POST variables
$_POST['Verb'] = 'spam';
$_POST['PluralNoun'] = 'eggs';
// original template with blanks (should be loaded from a valid XML file)
$xml = 'blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb>';
$valid_xml = '<?xml version="1.0"?><xml>' . $xml . '</xml>';
$doc = DOMDocument::loadXML($valid_xml, LIBXML_NOERROR);
if ($doc !== FALSE) {
$text = ''; // used to accumulate output while walking XML tree
foreach ($doc->documentElement->childNodes as $child) {
if ($child->nodeType == XML_TEXT_NODE) { // keep text nodes
$text .= $child->wholeText;
} else if (array_key_exists($child->tagName, $_POST)) {
// replace nodes whose tag matches a POST variable
$text .= $_POST[$child->tagName];
} else { // keep other nodes
$text .= $doc->saveXML($child);
}
}
echo $text . "\n";
} else {
echo "Failed to parse XML\n";
}
Here is PHP foreach syntax. Hope it helps
$arr = array('fruit1' => 'apple', 'fruit2' => 'orange');
foreach ($arr as $key => $val) {
echo "$key = $val\n";
}
and here is the code to loop thru your $_POST variables:
foreach ($_POST as $key => $val) {
echo "$key = $val\n";
// then you can fill each POST var to your XML
// maybe you want to use PHP str_replace function too
}
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 11 months ago.
Here's the json
[{"location":"USA","email":"test#test.com","sex":"male","age":"Unkown","other":null,"profile":{"net":["55","56"],"networks":[{"site_url":"http://site.com","network":"test","username":"mike"},{"site_url":"http://site.com/2","network":"test2","username":"mike2"}]},"name":"Mike Jones","id":111}]
I wanted to know how I could echo out all networks so it echos out the site_url,network, and user for each of the 2.
How would I get "name" at the end out of there as well?
Tanks!
Use json_decode()
http://php.net/manual/en/function.json-decode.php
$data = json_decode(...your sstring ...);
echo $data[0]->name;
Use json_decode to decode the JSON data. Then you can iterate the array with foreach and access the site_urls of each array item with another foreach like:
$arr = json_decode($json);
foreach ($arr as $obj) {
foreach ($obj->profile->networks as $network) {
echo $network->site_url;
}
}
http://lt2.php.net/json_decode
Here's a straight-forward example doing the two things that you ask for (see inline comments).
$json = '[{"location":"USA","email":"test#test.com","sex":"male","age":"Unkown","other":null,"profile":{"net":["55","56"],"networks":[{"site_url":"http://site.com","network":"test","username":"mike"},{"site_url":"http://site.com/2","network":"test2","username":"mike2"}]},"name":"Mike Jones","id":111}]';
// "Decode" JSON into (dumb) native PHP object
$data = json_decode($json);
// Get the first item in the array (there is only one)
$item = $data[0];
// Loop over the profile.networks array
foreach ($item->profile->networks as $network) {
// echos out the site_url,network, and user
echo "site_url = " . $network->site_url . PHP_EOL;
echo "network = " . $network->network . PHP_EOL;
echo "user = " . $network->username . PHP_EOL;
}
// Get "name" at the end
echo "name = " . $item->name . PHP_EOL;
It should output (if you're viewing as HTML, it will be munged onto one line… don't output as HTML).
site_url = http://site.com
network = test
user = mike
site_url = http://site.com/2
network = test2
user = mike2
name = Mike Jones
Building on aviv's answer...
$data = json_decode(...your sstring ...);
echo $data[0]->location; // USA
...
echo $data[0]->profile->net[0]; // 55
echo $data[0]->profile->net[1]; // 56
echo $data[0]->profile->networks[0]->site_url; // http://site.com
echo $data[0]->profile->networks[0]->network; // test
echo $data[0]->profile->networks[0]->username; // mike
echo $data[0]->profile->networks[1]->site_url; // http://site.com/2
echo $data[0]->profile->networks[1]->network; // test2
echo $data[0]->profile->networks[1]->username; // mike2
echo $data[0]->name; // Mike Jones