I'm loading event listing as an JSON-File from an URL:
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
?>
The direct output looks like this (more values and mor lines):
[{"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
{"id":"2","name":"NAME_2","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"}]
I need to search for all entrys with the value "name":"NAME_1" and print out the value of "booking_url".
I tried different things like array_seach() etc. but did not work out.
Any help is appreciated!
try this
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file, true);
foreach ($data as $r)
{
if ($r['name'] == 'NAME_1')
{
echo $r['booking_url'];
}
}
?>
The other option is to access your data in object context, thus:
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
foreach ($data as $r)
{
if ($r->name == 'NAME_1')
{
echo $r->booking_url;
}
}
?>
Either one should work just as well.
Related
I'm having some issues trying to unset a specific element from a JSON, what I have is something like that:
<?php
$json = '[{"contract":"0xb999803ee7087559eb601a4939c2d5da7668385a"},{"contract":"0x8880093d0759e485239d3010a47b80wesh5b6507daae"},{"contract":"0x77100c19ec711f0c4d6a4b38dad0b16f07aa74fe"}]';
$json_decode = json_decode($json, true);
foreach ($json_decode as $item => $value){
if ($value=='0x8880093d0759e485239d3010a47b80wesh5b6507daae')
{
unset($json_decode[$item]);
}
}
$json_decode = array_values($json_decode);
echo json_encode($json_decode);
?>
What I'd like to have afterwards is a JSON like this:
[{"contract":"0xb999803ee7087559eb601a4939c2d5da7668385a"},{"contract":"0x77100c19ec711f0c4d6a4b38dad0b16f07aa74fe"}]
Nevermind, my if statement was wrong, I had to do it like this:
if ($value['contract']=='0x8880093d0759e485239d3010a47b80wesh5b6507daae')
{
unset($json_decode[$item]);
}
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it
I have a directory of files who's main purpose is to store php variables for inclusion into other files in the site. Each file contains the same set of variables, but with different values.
for example:
event1.php
<?php
$eventActive = 'true';
$eventName = My First Event;
$eventDate = 01/15;
?>
event2.php
<?php
$eventActive = 'true';
$eventName = My Second Event;
$eventDate = 02/15;
?>
In addition to calling these variables in other pages, I want to create a page that contains a dynamic list, based on the variables stored in each file within the directory.
Something like (basic concept):
for each file in directory ('/events') {
if $eventActive = 'true'{
<p><? echo $eventName ?></p>
}
}
What is the best way to do this?
Create an Event class or an array of each event. Then populate it from the directory.
$index = 0;
foreach (array_filter(glob($dir.'/*'), 'is_file') as $file) {
#include $file; // Parses the file, so the variables within are set.
$events[$index]['active'] = $eventActive;
$events[$index]['name'] = $eventName;
$events[$index]['date'] = $evetnDate;
$index++;
// OR
// $events[] = new Event($eventName, $eventDate, $eventActive);
}
// Now the $events array contains all your events.
// List out the active ones
foreach ($events as $event) {
echo ($event['active'] === 'true') ? $event['name'] : '';
// OR
// echo $event->isActive() ? $event->getName() : '';
}
Ok, so I spend some time with it and was able to reslove the issue with a cleaner solution, but utilizing an external json file to store the values
<?php
$json = file_get_contents('events.json');
$jsonArray = json_decode($json, true); // decode the JSON into an associative array
foreach ($jsonArray as $value) {
if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {
echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
}
}
echo $currentDate;
?>
This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.
how can output of inside foreach with serialize store in database? next: called of database?
please give me example.
foreach($upload_data as $file) {
echo serialize($file['file']);
}
output: s:54:"Chrysanthemum6.jpg";s:47:"/Desert6.jpg";
With respect
Something like this?
$result = array();
foreach ($upload_data as $file) {
$result[] = $file['file'];
}
var_dump(serialize($result));
store the serialize in a variable?
$result = '';
foreach($upload_data as $file) {
$result .= serialize($file['file'];
}
echo $result;