I hope I'm right here.
I am making a search engine and take my Data from a json-file(url)
I can read out the text with my code (php)
<?php
foreach ($obj['Products'] as $key => $value) {
echo '<p>Artikel: '.$value['ProductName']. '</p> <br/>';
echo '<p> Produktbeschreibung: '.$value['Description'].'</p> <br/><br/>';
echo ' zum Shop <br/><br/>';
}
$service = "http://dateck-media.de/sf/ddd.php ;This is the JSON // Put together request $request = $service . "?" . http_build_query($params); Get response $response = file_get_contents($request,TRUE); $obj = json_decode($response,true);
but now i want to show the results of my search. in my json file it looks like
Array (
[ProductsSummary] => Array (
[Records] => 20
[TotalRecords] => 41
[TotalPages] => 3
[CurrentPage] => 1
)
[Products]
I don't know how to get the [Totalrecords] in my code to ECHO "You have [TotalRecords] for your search"
Please help me.
You could write the total as follows (outside of the loop you have):
echo "You have {$obj['ProductsSummary']['TotalRecords']} results for your search";
Thx to all and sorry for my English... now i will try to put the Total- and CurrentPages at the End of the search, to go forward to the next site! But first i try alone :-)
Related
I have a text file with following json data-
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}}
{"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}
I want to update 3rd record based on two criteria:
"id":"17"
"message":"update next"
Output of 3rd record I want -
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Meanwhile, please wait for our representative to get back to you."}}}
please help me to update the record with php.
First of all, you need to make a valid JSON
then you have to convert the JSON to an array
then you have to iterate through the array and find which item matches the criteria
and last you change the values.
JSON file content (filename: items.json):
[
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}},
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}},
{"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}},
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}
]
an example code is provided below:
<?php
$json = file_get_contents('items.json');
$json_as_array = json_decode($json, true);
$found = null;
foreach ($json_as_array as $key => $item)
{
if(strtolower($item['message']) == "update next" && $item['response']['recipient']['id'] == 17)
{
$found = $key;
}
}
$json_as_array[$found] = ["sender" => 175, "time" => 15, "message" => "office app", "response" => [ "recipient" => ["id" => 17], "message" => ["text" => "Meanwhile, please wait for our representative to get back to you."]]];
$json_output = json_encode($json_as_array);
file_put_contents('items.json', $json_output);
echo "Done!";
?>
i will not write all of the code but the proper way of storing the json , the way i do is
file_put_contents('appendData.txt', json_encode($inRadiusPostalCodes) , FILE_APPEND | LOCK_EX);
next when you read the file just read the file with
file_get_contents();
store it in a variable and then json_decode the string and then loop through your array to update record on desired index like
if($index == $someindex){......}
The data I have to work with looks like this:
<div><strong><?php echo $form_data['field'][86]);?></strong> - Guests find seats</div>
<div><strong><?php echo $form_data['field'][87];?></strong> - Bridal party introductions</div>
<div><strong><?php echo $form_data['field'][88];?></strong> - Dinner is served</div>
<div><strong><?php echo $form_data['field'][92];?></strong> - Cake cutting</div>
<div><strong><?php echo $form_data['field'][96];?></strong> - Speeches</div>
<div><strong><?php echo $form_data['field'][188];?></strong> - Blessing</div>
<div><strong><?php echo $form_data['field'][107];?></strong> - First Dances</div>
But that example data is rarely consistent. For example, there may not be a cake cutting, also the order as shown is not correct.
However, the $form_data values are ALWAYS 24 hour fomats (ie. 14:00, 03:30, etc.)
I want to be able to take all the existing strings (whichever one's are not blank) and create an array that includes the time and event type and then echoes the output in the correct order.)
So the array would always include those 7 string values, but there may be times that only 5 or 6 of them are relevant.
Thank you for any help you can provide.
How about this for an idea. I think I follow your question, but dont beat me up if I missed something.
Write a little PHP to create a seperate array from the relevant items from $form_data array, add the labels to that array as well so you know what you are putting out onto the page
<?php
$pickupList = array(86 => 'Guests find seats',
87 => 'Bridal party introductions',
88 => 'Dinner is served',
92 => 'Cake cutting',
96 => 'Speeches',
188 => 'Blessing',
107 => 'First Dances'
);
$event_order = array();
foreach ( $pickupList as $key=> $label ) {
if ( $form_data['field'][$key] != '' ) {
$event_order[$form_data['field'][$key]] = $label;
}
}
ksort($event_order); // sort on key which is a time 12:15
foreach ( $event_order as $time => $event) {
echo '<div><strong>';
echo $time;
echo '</strong> - ';
echo $event;
echo '</div>';
}
I parsing scores from http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383
I able to parse all the attributes. But I can't able to parse the time.
I Used
$homepages = file_get_html("http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383");
$teama = $homepages->find('span[id="clock"]');
Kindly help me
Since the that particular site is loading the values dynamically (thru AJAX request), you cant really parse the value upon initial load.
<span id="clock"></span> // this tends to be empty initial load
Normal scrapping:
$homepages = file_get_contents("http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383");
$doc = new DOMDocument();
#$doc->loadHTML($homepages);
$xpath = new DOMXPath($doc);
$query = $xpath->query("//span[#id='clock']");
foreach($query as $value) {
echo $value->nodeValue; // the traversal is correct, but this will be empty
}
My suggestion is instead of scraping it, you will need to have to access it thru a request also, since it is a time (of course, as the match goes on this will change and change until the game has ended). Or you can also use their request.
$url = 'http://sports.in.msn.com/liveplayajax/SOCCERMATCH/match/gsm/en-in/1597383';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
echo '<pre>';
print_r($data);
echo '</pre>';
Should yield something like (a part of it actually):
[2] => Array
(
[Code] =>
[CommentId] => -1119368663
[CommentType] => manual
[Description] => FULL-TIME: South Africa 0-5 Brazil.
[Min] => 90'
[MinExtra] => (+3)
[View] =>
[ViewHint] =>
[ViewIndex] => 0
[EditKey] =>
[TrackingValues] =>
[AopValue] =>
)
You should get the 90' by using foreach. Consider this example:
foreach($data['Commentary']['CommentaryItems'] as $key => $value) {
if(stripos($value['Description'], 'FULL-TIME') !== false) {
echo $value['Min'];
break;
}
}
Should print: 90'
{"99.net":{"status":"regthroughothers","classkey":"dotnet"},
"99.org": {"status":"regthroughothers","classkey":"domorg"},
"99.mobi":{"status":"regthroughothers","classkey":"dotmobi"},
"99.name":{"status":"Invalid Domain Name","classkey":"dotname"},
"99.us":{"status":"regthroughothers","classkey":"domus"},
"99.com":{"status":"regthroughothers","classkey":"domcno"},
"99.info":{"status":"Invalid Domain Name","classkey":"dominfo"},
"99.co.uk":{"status":"available","classkey":"thirdleveldotuk"},
"99.biz":{"status":"Invalid Domain Name","classkey":"dombiz"},
"99.in":{"status":"Invalid Domain Name","classkey":"dotin"}}
I'm able to display the output with the following code:
$json1 = json_decode($response1);
foreach($json1 as $key=>$sel_rows)
{
echo $key ;
echo " status: ". $sel_rows->status." ";
echo " Class: ". $sel_rows->classkey." ";
echo "Price";
echo "<br>";
}<br>
Now, I need to sort it so that a table such as the following can be shown:
<table border="1">
<tr>
<td>.com</td>
<td>.net</td>
<td>.info</td>
<td>.org</td>
</tr>
<tr>
<td>ADD</td>
<td>ADD</td>
<td>ADD</td>
<td>ADD</td>
</tr>
</table>
I'm having trouble figuring out how to sort the response in a way that I can use to generate this table, using the response data to add tool tips to the ADD links (like dinakar.com).
$json1 = json_decode($response1, TRUE);
foreach($json1 as $key=>$sel_rows)
{
echo $key ;
echo " status: ". $sel_rows['status']." ";
echo " Class: ". $sel_rows['classkey']." ";
echo "Price";
echo "<br>";
}
It looks like you're not having a problem decoding the response, but rather normalizing it for what you need to display. To do that, you'll need to extract the TLD from the domain string, unless you know it ahead of time. Presumably you do, as it was used to request the response to begin with?
Anyway, the following code illustrates one way of getting it into an array suitable for you to pass to your view (or however you're doing it):
$response1 = <<< EOF
{"99.net":{"status":"regthroughothers","classkey":"dotnet"},
"99.org": {"status":"regthroughothers","classkey":"domorg"},
"99.mobi":{"status":"regthroughothers","classkey":"dotmobi"},
"99.name":{"status":"Invalid Domain Name","classkey":"dotname"},
"99.us":{"status":"regthroughothers","classkey":"domus"},
"99.com":{"status":"regthroughothers","classkey":"domcno"},
"99.info":{"status":"Invalid Domain Name","classkey":"dominfo"},
"99.co.uk":{"status":"available","classkey":"thirdleveldotuk"},
"99.biz":{"status":"Invalid Domain Name","classkey":"dombiz"},
"99.in":{"status":"Invalid Domain Name","classkey":"dotin"}}
EOF;
function get_tld($url) {
$host = parse_url($url);
$domain = $host['path'];
$tail = substr($domain, -7); // Watch out, gotcha! Be sure of this.
$tld = strstr($tail, ".");
return $tld;
}
$domains = array();
$json1 = json_decode($response1);
foreach ($json1 as $idx => $obj) {
$tld = get_tld($idx);
$domains[$tld] = array('tld' => $tld, 'status' => $obj->status, 'classkey' => $obj->classkey);
}
This is off the top of my head. The resulting $domains array looks like this (truncated for brevity):
Array
(
[.net] => Array
(
[tld] => .net
[status] => regthroughothers
[classkey] => dotnet
)
[.org] => Array
(
[tld] => .org
[status] => regthroughothers
[classkey] => domorg
)
Note, I'm not doing a whole lot of sanity here, but that should be enough to help you sink your teeth into it. You'd then just make your table head off the keys, and populate your add links with whatever information they need that was returned in the response.
I have browsed around the suggested titles and found some answers but nothing that really worked, and so I turn to you...
I have a function that uses ob_start() to call a file from which the contents are used as a skeleton. Once the contents have been retrieved I use ob_end_clean().
I only seem to be getting output from the first time I call the function and nothing more afterwards. I have included a code dump in case I am doing something wrong.
I have also included a sample of what is returned from my database call ($dl->select ...)
I have also made sure that data is indeed being passed back from the database where I am expecting it to.
Array
(
[0] => Array
(
[rev_id] => 7
[rev_temp_tree_id] => 2
[rev_tree_id] =>
[rev_status] =>
[rev_last_updated_by] => 0
[rev_authorized_by] =>
[rev_date_updated] => 1334600174
[rev_date_reviewed] =>
[rev_update_type] => 1
[temp_tree_id] => 2
[temp_tree_bag_size] => 250
[temp_tree_botanical_id] =>
[temp_tree_stem_size] => 0
[temp_tree_crown] => 0
[temp_tree_price] => 0
[temp_tree_height] => 0
[temp_tree_plant_date] => 0
[temp_tree_review_id] =>
[temp_tree_comments] =>
[temp_tree_marked_move] => 0
[temp_tree_initial_location] =>
[temp_tree_coord] =>
[temp_tree_name] => TEST
[temp_tree_sale_status] => 0
[temp_tree_open_ground] =>
[temp_tree_block] => 0
[temp_tree_row] => 0
)
)
and the code...
<?php
function print_trees($trees){
$return = '';
ob_start();
include_once('skeletons/tree.html');
$tree_skeleton= ob_get_contents();
ob_end_clean();
$search=array("[tree_id]", "[tree_name]", "[Classes]", "[rev_id]");
foreach($trees as $t){
$replace=array($t['temp_tree_id'], $t['temp_tree_name'].' ['.$t['temp_tree_id'].']', 'temp_tree', $t['rev_id']);
$return.=str_replace($search,$replace,$tree_skeleton);
}
return $return;
}
switch ($_GET['mode']){
case 'trees' :
$db_status = '';
$new_trees = $dl->select('tree_review AS tr LEFT JOIN temp_tree_trees AS tt ON tr.rev_temp_tree_id=tt.temp_tree_id', 'tr.rev_update_type="1"');
echo '<h2>New Trees</h2>';
if($dl->totalrows>0){
echo print_trees($new_trees);
}
else{
echo 'no new trees for review';
}
echo '<br /><br />';
$new_trees = $dl->select('tree_review AS tr LEFT JOIN temp_tree_trees AS tt ON tr.rev_tree_id=tt.temp_tree_id', 'tr.rev_update_type="2"');
echo '<h2>Updated Trees</h2>';
if($dl->totalrows>0){
echo print_trees($new_trees);
}
else{
echo 'no update trees for review';
}
echo '<br /><br />';
$new_trees = $dl->select('tree_review AS tr LEFT JOIN temp_tree_trees AS tt ON tr.rev_tree_id=tt.temp_tree_id', 'tr.rev_update_type="3"');
echo '<h2>Moved Trees</h2>';
if($dl->totalrows>0){
echo print_trees($new_trees);
}
else{
echo 'no moved trees for review';
}
echo '<br /><br />';
$new_trees = $dl->select('tree_review AS tr LEFT JOIN temp_tree_trees AS tt ON tr.rev_tree_id=tt.temp_tree_id', 'tr.rev_update_type="4"');
echo '<h2>Duplicated Trees</h2>';
if($dl->totalrows>0){
echo print_trees($new_trees);
}
else{
echo 'no duplicated trees for review';
}
break;
}
?>
Any help would be appreciated.
Thanks in advance.
I believe it could be one of two things:
You might be having trouble with the fact that you're representing a multi-dimensional array as a string in the HTML file, and then attempting to operate on that with a string replace. You might be better off representing the file as a data structure (XML, JSON) and parsing apart that way - this will let you skip output buffering entirely.
Alternately, I'm not sure if $new_trees is an array of objects or something else. If it's an array of objects, the foreach() loop isn't going to work correctly i.e. it should be $t->temp_tree_id vs. $t['temp_tree_id']
thanks for your comments.
I found out what the problem was, it was rather stupid actually. The file that I am importing as a skeleton is included using include_once, so once I try to call it again it won't let me.
#minitech I updated my code as you suggested, thanks.
#gadhra the content in the skeleton file is plain html and im using keywords to replace the content from the db into the html. I should have attached the html along with my code.
Thanks again :)