PHP - Extract From Json Data
I am also trying to extract the "address_components" from the JSON data, but the array index changes if you do not submit an address line for example. I am trying to get the "sublocality" and "administrative_area_level_1" from the "address_components" below. The API sample is as follows: { "results" : [ { "access_points" : [], "address_components" : [ { "long_name" : "10", "short_name" : "10", "types" : [ "street_number" ] }, { "long_name" : "Gillespie Street", "short_name" : "Gillespie St", "types" : [ "route" ] }, { "long_name" : "South Beach", "short_name" : "South Beach", "types" : [ "political", "sublocality", "sublocality_level_1" ] }, { "long_name" : "Durban", "short_name" : "Durban", "types" : [ "locality", "political" ] }, { "long_name" : "Durban Metro", "short_name" : "Durban Metro", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "KwaZulu-Natal", "short_name" : "KZN", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "South Africa", "short_name" : "ZA", "types" : [ "country", "political" ] }, { "long_name" : "4001", "short_name" : "4001", "types" : [ "postal_code" ] } ], "formatted_address" : "10 Gillespie St, South Beach, Durban, 4001, South Africa", "geometry" : { "location" : { "lat" : -29.859728, "lng" : 31.039773 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : -29.8583790197085, "lng" : 31.0411219802915 }, "southwest" : { "lat" : -29.8610769802915, "lng" : 31.0384240197085 } } }, "place_id" : "ChIJGRCdW0mo9x4RcIwU_7S1xa8", "plus_code" : { "compound_code" : "42RQ+4W Durban, South Africa", "global_code" : "5G2H42RQ+4W" }, "types" : [ "street_address" ] } ], "status" : "OK" } If you submit a full address to the API, you can use the hard coded index like below: [7] $json_a['results'][0]['address_components'][7]['long_name'] But it is not reliable to hard code the index [7] in this case. So I tested some sample code from above post, it is working, but in some cases it does not return the "long_name" of the "sublocality" or "administrative_admin_level_1": /* if no address, then the array index change */ // $json_a['results'][0]['address_components'][7]['long_name'] $area = array(); foreach ($json_a['results'][0]['address_components'] as $addrObj) { foreach($addrObj['types'] as $type) { if (substr_count($type, 'sublocality')>0) { $area['short_name'] = $addrObj['short_name']; $area['long_name'] = $addObj['long_name']; // var_dump($addrObj); } if (substr_count($type, 'administrative_area_level_1')>0) { $area['short_admin'] = $addrObj['short_name']; $area['long_admin'] = $addObj['long_name']; var_dump($addrObj); } } } In the var_dump() I do get the long_name value though: In this sample it must be "Kwazulu-Natal", but from the code above, it returns a NULL value. array(3) { ["long_name"]=> string(13) "KwaZulu-Natal" ["short_name"]=> string(3) "KZN" ["types"]=> array(2) { [0]=> string(27) "administrative_area_level_1" [1]=> string(9) "political" } } Below is the full script I am trying to get to work. The lon, lng and format name is working 100%, it is just this array index problem. /* get google result in JSON*/ $googleString = file_get_contents($googleUrl); // get json content $json_a = json_decode($googleString, true); //json decoder // response status will be 'OK', if able to geocode given address if($json_a['status']=='OK'){ // get the important data $lati = isset($json_a['results'][0]['geometry']['location']['lat']) ? $json_a['results'][0]['geometry']['location']['lat'] : ""; $longi = isset($json_a['results'][0]['geometry']['location']['lng']) ? $json_a['results'][0]['geometry']['location']['lng'] : ""; $formatted_address = isset($json_a['results'][0]['formatted_address']) ? $json_a['results'][0]['formatted_address'] : ""; /* if no address, then the array index change */ // $json_a['results'][0]['address_components'][7]['long_name'] $area = array(); foreach ($json_a['results'][0]['address_components'] as $addrObj) { foreach($addrObj['types'] as $type) { if (substr_count($type, 'sublocality')>0) { $area['short_name'] = $addrObj['short_name']; $area['long_name'] = $addObj['long_name']; // var_dump($addrObj); } if (substr_count($type, 'administrative_area_level_1')>0) { $area['short_admin'] = $addrObj['short_name']; $area['long_admin'] = $addObj['long_name']; var_dump($addrObj); } } } Is there a better way to get the "sublocality" and "administrative_area_level_1" from the array $area array above. Any pointers will be much appreciated. Similar TutorialsHi, Anybody can help me to extract data from son using php
{"location":{"woeid":2293962,"city":"Kasaragod","region":" KL","country":"India","lat":12.5174,"long":74.990662,"timezone_id":"Asia/Kolkata"},"current_observation":{"wind":{"chill":80,"direction":338,"speed":11.81},"atmosphere":{"humidity":70,"visibility":10.0,"pressure":29.8,"rising":0},"astronomy":{"sunrise":"6:54 am","sunset":"6:35 pm"},"condition":{"text":"Clear","code":31,"temperature":80},"pubDate":1549638000},"forecasts":[{"day":"Fri","date":1549564200,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sat","date":1549650600,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sun","date":1549737000,"low":75,"high":85,"text":"Sunny","code":32},{"day":"Mon","date":1549823400,"low":76,"high":87,"text":"Mostly Sunny","code":34},{"day":"Tue","date":1549909800,"low":76,"high":89,"text":"Sunny","code":32},{"day":"Wed","date":1549996200,"low":77,"high":88,"text":"Partly Cloudy","code":30},{"day":"Thu","date":1550082600,"low":76,"high":89,"text":"Mostly Sunny","code":34},{"day":"Fri","date":1550169000,"low":76,"high":86,"text":"Sunny","code":32},{"day":"Sat","date":1550255400,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sun","date":1550341800,"low":74,"high":85,"text":"Sunny","code":32}]}
How to extract data of "current_observation"
Thanks So I have been working on my website for a while which all is php&mysql based, now working on the social networking part building in similar functions like Facebook has. I encountered a difficulty with getting information back from a link. I've checked several sources how it is possible, with title 'Facebook Like URL data Extract Using jQuery PHP and Ajax' was the most popular answer, I get the scripts but all of these scripts work with html links only. My site all with php extensions and copy&paste my site links into these demos do not return anything . I checked the code and all of them using file_get_contents(), parsing through the html file so if i pass 'filename.php' it returns nothing supposing that php has not processed yet and the function gets the content of the php script with no data of course. So my question is that how it is possible to extract data from a link with php extension (on Facebook it works) or how to get php file executed for file_get_contents() to get back the html?
here is the link with code&demo iamusing: http://www.sanwebe.c...-php-and-jquery
thanks in advance.
I can t seem to get this. I need to extract some data from the following xml file. http://api.twitter.com/1/users/show/seobpo.xml I just want to get seobpo's tweet count. The data will be used in a wordpress blog. Thank you There is a web page that is programmed in ASP and has a simple one field form (drop down list) and a submit button. After you submit the form by selecting an option (over 150 options), it will take you to the result page using the "Post" method. The variable does not show in the result page URL. The result page has table with multiple columns. What I want is to have ALL the results in one CSV file. Here what I really need in details: 1- Import all tables (one table for each option in the drop-down list) into a CSV file. 2- The content of two columns has codes. Replace all the codes in the table to a separate column. 3- Create an additional column that contains the name of the option on the first page form. I need to have it in a php file so that I can run it via cron job few times a year. How can I obtain this functionality with PHP? I want to get loop numbers and hyperlinks from other included file function how to call function that gives me all 1-10 numbers and hyperlinks thanks Code: [Select] <?php include('linksandid.php'); idlink(); here i want get all numbers and hyperlinks separately ?> linksandid.php: Code: [Select] <?php function idlink() { for($i =1; $i <= 10; $i ++) { $links = "<a href=\"http://localhost\123.php?page=$i\"> $i</a> "; } ?> Is it possible to write a php script that would extract data from an external web page. I've been working with php for a few years as a hobby, but I've never seen this done or needed a reason to until now. Thanks in advance for any responses. I'm trying to build a calculator for a game...but I'm stuck on the extracting part. I don't really know what it's called (so if you know of a tutorial/handbook please link), but how I would I extract this data: //data to extract $name = "Robin hood hat" $currentprice = "3.3m" $change = "+11.5k" //display echo $name echo $currentprice echo $change from: http://itemdb-rs.runescape.com/results.ws?query=robin hood hat And a small question: how would I convert "+11.5k" into "11500" (1k = 1,000)? The * multiplies it but how do I check for and remove the "+" and "k"? Hello, This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=350672.0 Hello everyone, I have been trying several things,recently, and I can't figure out how to get a series of numbers, grouped together as a string of number, instead of it adding or grabbing the last number that was randomly generated. I'm wanting to save it in a variable (of course), so I can pass it though a query when it is needed. foreach($array as $number){ echo $number; } $array is the variable where it is an array but all the randomly generated numbers are stored there. All / any help would be gratefully appreciated. how could I get the next days forecasted high and low temp from this feed into php variables? feed://view/1292654647//http://newsrss.bbc.co.uk/weather/forecast/2818/Next3DaysRSS.xml any help appreciated. thanks in advance. Hi, I want to extract weather for 5 cities from www.wunderground.com/global/SB.html and put the field data such as colombo, temprature, humidity and conditions in to a mysql table so I can display the weather for this 5 cities and automatically set a cronjob to update it everyday. Issue is I am unable to extract the specific data from this page. Please help. thanks Hi Everyone, I have just started using Simple HTML DOM today and I have spent 4 hours not getting what I want. I want to be able to extract the following information: Code: [Select] <div class="listing_content"> <span class="serialNumb" style="line-height: 21px;">77777</span> <br /> 444 ASDF, Alpha, Tango, Beta <br /> 77777 Director:99999 <div> <img title='web' src='http://cpgimg.com/images/icon_sm_web.gif' alt='web'/> <a href='javascript:void(0)' onClick="window.open('/redir.jsp?p_url=http:%2f%2fwww.cnn.com&p_cid=2707304&p_hid=279E00&p_ct=3527&p_pr=KO&p_fr=U');" class='listing_link'>website</a> <img title='email' src='http://cpgimg.com/images/icon_sm_mail.gif' alt='email'/> <a class='listing_link' href="javascript:void(0)" onclick="popupEmail('/email.jsp?lang=0&p_cid=2707304');(new Image()).src='/redir.jsp?p_url=&p_cid=2707304&p_hid=279E00&p_ct=3527&p_pr=ON&p_fr=E&msec='+(new Date()).getMilliseconds()">E-mail</a> </div> </div> The content I need to pull separately from above include: 1- serialNumb = 77777 2- 444 ASDF, Alpha, Tango, Beta 3- 77777 Director:99999 4- www.cnn.com I want all the data to recorded to different variables so I can upload them to MySQL. Any help with this is much appreciated. I don't have to use Simple DOM HTML but per my search it seems to be the best tool (however, I am not so lucky with it.) ***Not to forget that this page is full of <div>, <br />, <img>, and other tags. The quoted part is just one excerpt but this part is unique and used once in the page "style="line-height: 21px;". Also the "('/redir.jsp?p_url" is also unique for the URL portion. Thanks again. Geek Friends, I have list of URLs in an array called '$domains' 1- I want to run through each and every element of $domains in an API call. API: Quote http://lightapi.majesticseo.com/api_command.php?app_api_key=API_KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majesticseo.com (Note: In this API "http://www.majesticseo.com" will be replaced with each element of $domain array in a loop) 2- The resulting output is XML: <?xml version="1.0" encoding="utf-8"?> <Result Code="OK" ErrorMessage="" FullError=""> <GlobalVars IndexBuildDate="17/04/2010 16:43:46" MostRecentBackLinkDate="2010-03-25"/> <DataTables Count="1"> <DataTable Name="Results" RowsCount="1" Headers="ItemNum|Item|ResultCode|Status|ExtBackLinks|RefDomains|AnalysisResUnitsCost|ACRank|ItemType|IndexedURLs|GetTopBackLinksAnalysisResUnitsCost|RefIPs|RefSubNets|RefDomainsEDU|ExtBackLinksEDU|RefDomainsGOV|ExtBackLinksGOV|RefDomainsEDU_Exact|ExtBackLinksEDU_Exact|RefDomainsGOV_Exact|ExtBackLinksGOV_Exact"> <Row>0|majesticseo.com|OK|Found|28381|1229|28381|-1|1|4774|28381|1074|954|1|5|0|0|0|0|0|0</Row> </DataTable> </DataTables> </Result> I want to extract the below Elements out of this XML Output for each element of $domains in loop: Quote ACRank ExtBackLinks RefDomains AnalysisResUnitsCost RefIPs RefSubNets RefDomainsEDU ExtBackLinksEDU RefDomainsGOV ExtBackLinksGOV RefDomainsEDU_Exact ExtBackLinksEDU_Exact RefDomainsGOV_Exact ExtBackLinksGOV_Exact LastCrawlDate Title How can i achieve this with PHP? P.S.: I have a scrapper code, that will scrape data for the array $domains, it best if we can merge this code with that code, so all run in one code only. Please Letme know and i will PM you that scrapper Code, as i do not want to share that Publically. Cheers & Enjoy the Snow , Natasha T Hi, Hope somebody can help me because I am relatively new to PHP and I am currently unsure how to implement the following: Let's assume I have a table like this id_number, name, data1, data2. When displayed on HTML page: Column id_number should be hidden. Column name is a link. When you click on this column then value stored in id_number should be used in a query to database. Result should be displayed below the link on the same page. When clicked again data should hide. I have some idea how to toggle visibility with a simple javascript function. How do i populate the table with hidden data and then extract it later on? Any help or suggestions are appreciated. Thanks. Hi guys, I want to generate reports and i want to use some fields of one table and other fields of another table. How can i use that? Ex. customer(customer_id, full_name,name_with_initials, address, contact_number,gender) transaction_table(tran_ID, account_number,account_type,transaction_type, amount, Date) If i want to use only customer_id, tran_ID, full_name and amount how can i use them to generate reports. I want them to be taken as fields of one table and use it.. Thanks, Heshan <?php ini_set('display_errors', 0); function escapeArray($array) { foreach ($array as $key => $val) { if(is_array($val)){ $array[$key]=escapeArray($val); } else{ $array[$key]=addslashes($val); } } return $array; } $request_type=$_SERVER['REQUEST_METHOD']; $api_key=$_SERVER['HTTP_X_API_KEY']; $res=array(); if($api_key!=="643256432"){ $res['msg']="Failu Invalid API KEY"; echo json_encode($res); die; } // Connects to the orcl service (i.e. database) on the "localhost" machine //$conn = oci_connect('SCOTT', 'admin123', 'localhost/orcl'); $conn = oci_connect('test', 'test', '192.168.10.43/test.test.com'); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); } $request=file_get_contents("php://input"); $request=escapeArray(json_decode($request,true)); print_r($request); // die; if($request_type=="POST"){//for creation of invoice echo $CONTACT_ID=isset($request['CONTACT_ID'])?$request['CONTACT_ID']:""; $INV_SERIAL_NO=isset($request['INV_SERIAL_NO'])?$request['INV_SERIAL_NO']:""; $NAME=isset($request['NAME'])?$request['NAME']:""; $INV_DATE=isset($request['INV_DATE'])?$request['INV_DATE']:""; $DUE_DATE=isset($request['DUE_DATE'])?$request['DUE_DATE']:""; $CURRENCY=isset($request['CURRENCY'])?$request['CURRENCY']:""; $SUBTOTAL=isset($request['SUBTOTAL'])?$request['SUBTOTAL']:""; $TAX_TOTAL=isset($request['TAX_TOTAL'])?$request['TAX_TOTAL']:""; echo $SHIP_SERIAL_NO=isset($request['SHIP_SERIAL_NO'])?$request['SHIP_SERIAL_NO']:""; $MASTER_NO=isset($request['MASTER_NO'])?$request['MASTER_NO']:""; $HOUSE_NO=isset($request['HOUSE_NO'])?$request['HOUSE_NO']:""; $shipment_data=isset($request['shipment_data'])?$request['shipment_data']:""; if($CONTACT_ID==""){ $res['msg']="CONTACT_ID is required"; } else if($INV_SERIAL_NO==""){ $res['msg']="INV_SERIAL_NO is required"; } else if($NAME==""){ $res['msg']="NAME is required"; } else if($INV_DATE==""){ $res['msg']="INV_DATE is required"; } else if($DUE_DATE==""){ $res['msg']="DUE_DATE is required"; } else if($CURRENCY==""){ $res['msg']="CURRENCY is required"; } else if($SUBTOTAL==""){ $res['msg']="SUBTOTAL is required"; } else if($TAX_TOTAL==""){ $res['msg']="TAX_TOTAL is required"; } else if($MASTER_NO==""){ $res['msg']="MASTER_NO is required"; } else if($HOUSE_NO==""){ $res['msg']="HOUSE_NO is required"; } else if($SHIP_SERIAL_NO==""){ $res['msg']="SHIP_SERIAL_NO is required"; } else{ $stid = oci_parse($conn, "Select * from FL_HDR_INVOICE where CONTACT_ID='$CONTACT_ID'"); (oci_execute($stid)); oci_fetch_all($stid, $out); if(count($out['CONTACT_ID'])==0){ $stid = oci_parse($conn, "Insert into FL_HDR_INVOICE (CONTACT_ID,INV_SERIAL_NO,NAME,INV_DATE,DUE_DATE,CURRENCY,SUBTOTAL,TAX_TOTAL) Values ('$CONTACT_ID','$INV_SERIAL_NO','$NAME',TO_DATE('$INV_DATE','YYYY-MM-DD'),TO_DATE('$DUE_DATE','YYYY-MM-DD'),'$CURRENCY','$SUBTOTAL','$TAX_TOTAL')"); oci_execute($stid); $stid_2 = oci_parse($conn, "Insert into FL_SHIPMENT_DATA (CONTACT_ID,INV_SERIAL_NO,SHIP_SERIAL_NO,MASTER_NO,HOUSE_NO) Values ('$CONTACT_ID','$INV_SERIAL_NO','$SHIP_SERIAL_NO','$MASTER_NO','$HOUSE_NO')"); oci_execute($stid_2); if(oci_num_rows($stid)>0){ $res['msg']="Invoice created successfully against this contact_id:".$CONTACT_ID; } else{ $res['msg']="Something going wrong please try again later"; } } else{ $res['msg']="contact_id must be unique"; } } echo json_encode($res); die; } I need to read json data inside an array. Please help correct my code.. i am trying to do an API. Hi, I have a problem with some code not working. I need it to get the data from a mysql database and then export it as a json array in the format of id , title, author, date, imageUrl, text. (Please not that these are all variables ) PHP CODE: Code: [Select] <?php $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $arr = array(); $rs = ("SELECT `id`, `title`, `author`, `date`, `imageUrl`, `text` FROM `items`"); while($obj = mysql_query($rs)) { $arr[0] = $obj->id; $arr[1] = $obj->title; $arr[2] = $obj->author; $arr[3] = $obj->date; $arr[4] = $obj->imageUrl; $arr[5] = $obj->text; } echo '{"items":'.json_encode($arr).'}'; ?> Thanks For Your Help borden0108 Hi- I have to post to a URL, grab one field our of the JSON output/response and format nicely to the user. I've tried a few things with some help but none seem to be working. So any help or direction would be greatly appreciate it!! Attempt 1 (works but not formatted nicely) if I post using the browser, it works. the data is sent to the URL (web service) and I can see in the web service logs that the entry has been recorded. the problem is that since i have the URL in "action", i'm taken to that page and the user gets to see the JSON output Code: [Select] //here's the HTML form in offer.php <form action="http://somewebservice.com/<?php echo $PrizeID;?>" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the output (JSON) after clicking submit {"Prize":"XXXXXX","ConfirmationCode":"######","Error":false,"ErrorMsg":null} Attempt 2 (doens't work) i tried using php but after submit, the page refreshes and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> //here's the php in offer.php <?php if(isset($_POST['submit'])){ $options = array( 'http'=>array( 'method'=>"POST", 'content'=>http_build_query(array( 'account' => $account, 'dob' => $dob, 'site' => $site )) )); $context = stream_context_create($options); $result = file_get_contents("http://somewebservice.com/{$PrizeID}",NULL,$context); var_dump($result); } ?> Last attempt (doesn't work) i tried using php & curl so that i can process in the back and show only the ConfirmationCode to the user in a nice format but it doesn't work. after submit, i'm taken to process.php where i see nothing and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form action="process.php" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the PHP in process.php <?php $postvars=file_get_contents("php://input"); $curl=curl_init("http://somewebservice.com/{$PrizeID}"); curl_setopt($curl,CURLOPT_POSTFIELDS,$postvars); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result=curl_exec($curl); $decodedresult=json_decode($result,true); ?> i haven't gotten to the point where i grab the ConfirmationCode I want because i want to get this fixed first and also because i can't get that to work but will focus on that once i fix this. Thanks. |