PHP - Parsing Problem With A Php Array
I have a situation were I need to just get a simple location. I don't want any while loops or any of that jazz. I just want 1 string location every time. <?php $ider = $_GET['id']; $conn = mysqli_connect("localhost", "Me", "pass", "MyDB"); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT Location FROM LifeSaver1 WHERE id =$ider"; $result = $conn->query($sql); $obj = mysqli_fetch_object($result); $obj2 = $obj->Location; var_dump($obj); ?> This is what it outputs Quotestring(11) "Boston" I just need Boston. Can anyone give me a hint? Similar TutorialsFolks, I want to parse a particular element from an array and nothing else. Here is the Class (RecursiveTwitterSearch.php): <? /** * Wrapper class around the Twitter Search API for PHP * Based on the class originally developed by David Billingham * and accessible at http://twitter.slawcup.com/twitter.class.phps * @author Ryan Faerman <ryan.faerman@gmail.com> * @version 0.2 * @package PHPTwitterSearch */ class TwitterSearch { /** * Can be set to JSON (requires PHP 5.2 or the json pecl module) or XML - json|xml * @var string */ var $type = 'json'; /** * It is unclear if Twitter header preferences are standardized, but I would suggest using them. * More discussion at http://tinyurl.com/3xtx66 * @var array */ var $headers=array('X-Twitter-Client: PHPTwitterSearch','X-Twitter-Client-Version: 0.1','X-Twitter-Client-URL: http://ryanfaerman.com/twittersearch'); /** * Recommend setting a user-agent so Twitter knows how to contact you inc case of abuse. Include your email * @var string */ var $user_agent=''; /** * @var string */ var $query=''; /** * @var array */ var $responseInfo=array(); /** * Use an ISO language code. en, de... * @var string */ var $lang; /** * The number of tweets to return per page, max 100 * @var int */ var $rpp; /** * The page number to return, up to a max of roughly 1500 results * @var int */ var $page; /** * Return tweets with a status id greater than the since value * @var int */ var $since; /** * Returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers) * @var string */ var $geocode; /** * When "true", adds "<user>:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is "false" * @var boolean */ var $show_user = false; /** * @param string $query optional */ function TwitterSearch($query=false) { $this->query = $query; } /** * Find tweets from a user * @param string $user required * @return object */ function from($user) { $this->query .= ' from:'.str_replace('@', '', $user); return $this; } /** * Find tweets to a user * @param string $user required * @return object */ function to($user) { $this->query .= ' to:'.str_replace('@', '', $user); return $this; } /** * Find tweets referencing a user * @param string $user required * @return object */ function about($user) { $this->query .= ' @'.str_replace('@', '', $user); return $this; } /** * Find tweets containing a hashtag * @param string $user required * @return object */ function with($hashtag) { $this->query .= ' #'.str_replace('#', '', $hashtag); return $this; } /** * Find tweets containing a word * @param string $user required * @return object */ function contains($word) { $this->query .= ' '.$word; return $this; } /** * Set show_user to true * @return object */ function show_user() { $this->show_user = true; return $this; } /** * @param int $since_id required * @return object */ function since($since_id) { $this->since = $since_id; return $this; } /** * @param int $language required * @return object */ function lang($language) { $this->lang = $language; return $this; } /** * @param int $n required * @return object */ function rpp($n) { $this->rpp = $n; return $this; } /** * @param int $n required * @return object */ function page($n) { $this->page = $n; return $this; } /** * @param float $lat required. lattitude * @param float $long required. longitude * @param int $radius required. * @param string optional. mi|km * @return object */ function geocode($lat, $long, $radius, $units='mi') { $this->geocode = $lat.','.$long.','.$radius.$units; return $this; } /** * Build and perform the query, return the results. * @param $reset_query boolean optional. * @return object */ function results($reset_query=true) { $request = 'http://search.twitter.com/search.'.$this->type; $request .= '?q='.urlencode($this->query); if(isset($this->rpp)) { $request .= '&rpp='.$this->rpp; } if(isset($this->page)) { $request .= '&page='.$this->page; } if(isset($this->lang)) { $request .= '&lang='.$this->lang; } if(isset($this->since)) { $request .= '&since_id='.$this->since; } if($this->show_user) { $request .= '&show_user=true'; } if(isset($this->geocode)) { $request .= '&geocode='.$this->geocode; } if($reset_query) { $this->query = ''; } return $this->objectify($this->process($request))->results; } /** * Returns the top ten queries that are currently trending on Twitter. * @return object */ function trends() { $request = 'http://search.twitter.com/trends.json'; return $this->objectify($this->process($request)); } /** * Internal function where all the juicy curl fun takes place * this should not be called by anything external unless you are * doing something else completely then knock youself out. * @access private * @param string $url Required. API URL to request * @param string $postargs Optional. Urlencoded query string to append to the $url */ function process($url, $postargs=false) { $ch = curl_init($url); if($postargs !== false) { curl_setopt ($ch, CURLOPT_POST, true); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs); } curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_NOBODY, 0); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); $response = curl_exec($ch); $this->responseInfo=curl_getinfo($ch); curl_close($ch); if( intval( $this->responseInfo['http_code'] ) == 200 ) return $response; else return false; } /** * Function to prepare data for return to client * @access private * @param string $data */ function objectify($data) { if( $this->type == 'json' ) return (object) json_decode($data); else if( $this->type == 'xml' ) { if( function_exists('simplexml_load_string') ) { $obj = simplexml_load_string( $data ); $statuses = array(); foreach( $obj->status as $status ) { $statuses[] = $status; } return (object) $statuses; } else { return $out; } } else return false; } } class RecursiveTwitterSearch extends TwitterSearch { var $request_count = 0; var $max_request_count = 5; var $max_id; function recursive_results() { $request = 'http://search.twitter.com/search.'.$this->type; $request .= '?q='.urlencode($this->query); if(isset($this->rpp)) { $request .= '&rpp='.$this->rpp; } if(isset($this->page)) { $request .= '&page='.$this->page; } if(isset($this->lang)) { $request .= '?='.$this->lang; } if(isset($this->since)) { $request .= '&since_id='.$this->since; } if($this->show_user) { $request .= '&show_user=true'; } if(isset($this->geocode)) { $request .= '&geocode='.$this->geocode; } if(isset($this->max_id)) { $request .= '&max_id='.$this->max_id; } $response = $this->objectify($this->process($request)); $this->request_count++; if ($response) { $results = $response->results; if(!empty($response->next_page)) { preg_match('|\?page=([0-9]*)&max_id=([0-9]*)&|', $response->next_page, $matches); $this->page = $matches[1]; $this->max_id = $matches[2]; if ($this->request_count < $this->max_request_count) { $results = array_merge($results, $this->recursive_results()); } } return $results; } else return false; } function max_request_count($n) { $this->max_request_count = $n; return $this; } } ?> Here is how i am calling it: <?php require ("RecursiveTwitterSearch.php"); $rts = new RecursiveTwitterSearch('paintball mask'); echo '<pre>'; print_r($rts->recursive_results()); echo '</pre>'; echo 'It took ' . $rts->request_count . ' request(s) to get this result.'; ?> If you observer the Output, u will see lot of array, i want to extract only "[text]" portion. So the desired output should be like: Quote vPaintball Mask http://bit.ly/czBA6S The Paintball Republic does a short video about mask safety. LEARN. http://fb.me/KkMvjDWF airsoft vs paintball mask http://goo.gl/fb/tyoxk @mmorgansmithh like wearing a paintball mask on your head to starbucks Tippmann US Army Ranger Paintball Goggle Mask - Camo: Tippmann US Army Ranger Paintball Goggle Mask - Camo ... http://bit.ly/9hFi3p and so on......... Infact, i prfer to use "foreach" to each each element so i can do further operation on it. Can anyone help to achieve this? Natty Hi, Need help in parsing the . I am new to php and need to parsing and print only few elements in the arrary I have an array as below: Array ( [@attributes] => Array ( [WARRANTYCATEGORY] => Customer Warranty [NA_RATING] => [TAGCATEGORY1] => [TAGCATEGORY1DESC] => [TAGCATEGORY2] => [RESPONSEDATE] => 08-14-2006 04:40:40 PM [CASEID] => 1435435 [DUTYMANAGERAPPROVALTEXT] => [COUNTER] => 0 [DESCRIPTION] => SPRLSL:Cluster Notification [NA_BUGNO] => [PRIORITY] => 3 [WARRANTYPRODUCT] => WARR36MTH_HW_DISK [NA_DISRUPTION_EVENT] => [SERIALNUMBER] => 123456789 [NADUPCASEID] => [DMGERAPPRL] => [SYSNAME] => REWSRAPP34 [DATECLOSED] => 08-17-2006 04:47:37 PM [CASE_STATUSTEXT] => Closed [NASUPPORTOFFERING] => ST [CREATEDBY] => ) ) I need to access only CASEI D, CASE_STATUSTEXT and DATECLOSED from the above array How can I access that ? Thanks and Regards, Usha I have the following code below: hi. Basically, I am trying to set up a random bible verse script. I found an rss/xml feed he http://www.mybiblescripture.com/rss/bible.php?fmt=daily&trans=KJV Using the following code, I am attempting to parse the feed in to an array: Code: [Select] <?php function fetchXML($url) { //initialize library $ch = curl_init(); //used to make us look like a browser $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"; //set the url curl_setopt ($ch, CURLOPT_URL, $url); //set that I want to wait for a response curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); //make us look like a web browser curl_setopt ($ch, CURLOPT_USERAGENT, $useragent); //get data $data = curl_exec($ch); //clean up curl_close($ch); //return xml data return $data; } define("USE_CURL", true); $url = "http://www.mybiblescripture.com/rss/bible.php?fmt=daily&trans=KJV"; //get xml doc with info $data = fetchXML($url); //create a SimpleXML object to parse the xml $char_xml = new SimpleXmlElement($data); echo print_r($char_xml); ?> Which gives me the following output: Code: [Select] SimpleXMLElement Object ( [@attributes] => Array ( [version] => 2.0 ) [channel] => SimpleXMLElement Object ( [title] => My Bible Scripture - Bible Verse of the Day (KJV) [link] => http://www.mybiblescripture.com/ [description] => Verse of the Day - King James Version [language] => en-us [pubDate] => SimpleXMLElement Object ( ) [generator] => CPG-Nuke Dragonfly [copyright] => My Bible Scripture [category] => Religion [image] => SimpleXMLElement Object ( [width] => 111 [height] => 40 [url] => http://www.mybiblescripture.com/images/logo.gif [title] => My Bible Scripture [link] => http://www.mybiblescripture.com/ ) [item] => Array ( [0] => SimpleXMLElement Object ( [title] => Corinthians I 10:17 [link] => http://www.mybiblescripture.com/Bible/l_op=view-verse/lid=29613/trans=KJV.html [description] => For we being many are one bread, and one body: for we are all partakers of that one bread. (KJV) [pubDate] => SimpleXMLElement Object ( ) ) [1] => SimpleXMLElement Object ( [title] => Bible Verses [link] => http://www.mybiblescripture.com [description] => Find more Bible Scripture [pubDate] => Fri, 11 Mar 2011 00:45:06 GMT ) ) ) ) 1 What I am trying to do is pull ONLY [title] => Corinthians I 10:17 and its accompanying verse [description] => For we being many are one bread, and one body: for we are all partakers of that one bread. (KJV). I am very bad at trying to read multi-dim arrays and can't for the life of me figure out how to print the aforementioned keys. Could anyone help me here? thanks i am trying to get values from the json array that get direct messages from twitter but i am getting the message error "Parse error: syntax error, unexpected T_AS, expecting '(' " in relation to the line "foreach (array as $direct_message) {" Also should i convert the array into a linear php array? Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->get('https://api.twitter.com/1/direct_messages.json?count=1&page='); function write_into_database ($direct_message) { $conn = mysql_connect("127.0.0.1", "Diego", "frafra") or die(mysql_error()); mysql_select_db('bot', $conn) or die(mysql_error()); foreach(array as $direct_message) { mysql_query("INSERT INTO 'followers' ('user_id', 'user_alias'), VALUES ('{$direct_message->sender_id}', '{$direct_message->sender_screen_name}, INSERT INTO 'd_messages'('message_id', 'message'), VALUES ('{$direct_message->id}' ,'{$direct_message->text})"); } write_into_database($direct_message); I'm practicing some code here Code: [Select] reset($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "";) $val = "NULL"; $arVals[$key] = (get_magic_qqotes_gpc()) ? $val : addslashes($val); if($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($key != "access_period" && $key != "passwd") $arVals[$key] = "'".$arVals[$key]."'"; } And it's giving me error Quote Parse error: parse error in C:\wamp\www\php\user_registration\registered.php on line 26 line 26 is the Code: [Select] if ($val == "";) $val = "NULL"; I wonder what the problem is... Hi,
Well, I've been wondering if I can get answer to my problem here...
I'd used curl to fetch information from other site and then I need to parse the data to be displayed in our own. However I found something odd...I can't parse it to get what I want...however should I put the result into a html file, n parse the file itself...it's fine.
Basically I just need to find whether a word/phrase is there or not...n I'm using preg_match to do it so far. Since the time it first arises...I'd been googling n saw some posts...something similar to how regex is doing poorly in doing such thing...
However it does work when I just make a php file just to do that regex from the curl-result html file, it just not work on the actual php file which handle the process even if it's from the same curl-result html file. FYI, I'm using codeigniter.
I wonder if it got something to do with codeigniter or something...or is there any other better way to parse a html file from a curl result. In my opinion it's just the same...be it a curl result or just a normal html...so I really can't figure out where it went wrong.
I appreciate if there's anyone who can shed a light on this problem, even a little bit is a great help to me
Thanks in advance,
First, apologies if this is in the wrong section, basically I am not sure what language my problem lies! Here is the general over view. I have a jquery script that automatically selects a group of sub categorys and pus them in a select list depending on the input of a first select list, so you can choose you main cat and then the sub cats for this cat appear in the next list, this all works fine, the basic code is below: Code: [Select] <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("scripts/func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> <form action='do.php' method='post'> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="images/ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> This calls scripts/func.php Code: [Select] <?php //************************************** // Page load dropdown results // //************************************** function getTierOne() { $result = mysql_query("SELECT * FROM blog_cats") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['cat_id'].'">'.$tier['cat_name'].'</option>'; } } //************************************** // First selection results // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('../connect.php'); $result = mysql_query("SELECT * FROM blog_subs WHERE cat_id='$drop_var'") or die(mysql_error()); echo '<select name="tier_two" id="tier_two"> <option value=" " disabled="disabled" selected="selected">Select Sub Catergory</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['sub_id'].'">'.$drop_2['sub_name'].'</option>'; } echo '</select> '; } ?> The problem I am having is getting the second select (tier_two) to pass to my form processing page. I just get an undefined variable error Many Thanks Hey there, I am using prototype to send JSON information to a PHP file which will then use the data to update a database, the AJAX presently looks as follows: Code: [Select] function saveprofile() { var email = document.getElementById("email").value; var profileDetails = { "email":email, "titleitalic":titleitalic, "profileDetails":titlefontcolor, "titlefontcolor":titleunderline, "titleoffsettop":titleoffsettop, "titleoffsetleft":titleoffsetleft, "aboutbackgroundcolour":aboutbackgroundcolour, "aboutunderline":aboutunderline, "aboutfontfamily":aboutfontfamily, "aboutbold":aboutbold, "aboutitalic":aboutitalic, "aboutfontcolor":aboutfontcolor, "aboutoffsettop":aboutoffsettop, "aboutoffsetleft":aboutoffsetleft, "statusoffsetleft":statusoffsetleft, "statusinfooffsetright":statusinfooffsetright, "pictureoffsetleft":pictureoffsetleft, "profilebold":profilebold, "profileunderline":profileunderline, "profileitalic":profileitalic, "profilefontcolor":profilefontcolor, "profilefontfamily":profilefontfamily, "profilebackgroundcolour":profilebackgroundcolour } var jsonstring = JSON.stringify(profileDetails); alert(jsonstring); var request = new Ajax.Request ('scripts/updateprofile.php', { method: 'POST', parameters: jsonstring, onComplete: responseReturned } ); } Which outputs the following JSON which has been tested on http://www.jsonlint.com/ as valid: Code: [Select] { "email": "l-wilson-1986@hotmail.co.uk", "titleitalic": "normal", "profileDetails": "#d0deea", "titlefontcolor": "none", "titleoffsettop": 100, "titleoffsetleft": 100, "aboutbackgroundcolour": "transparent", "aboutunderline": "none", "aboutfontfamily": "Arial", "aboutbold": "normal", "aboutitalic": "normal", "aboutfontcolor": "#d0deea", "aboutoffsettop": 325, "aboutoffsetleft": 100, "statusoffsetleft": 450, "statusinfooffsetright": 250, "pictureoffsetleft": 100, "profilebold": "normal", "profileunderline": "none", "profileitalic": "normal", "profilefontcolor": "#fff", "profilefontfamily": "Arial", "profilebackgroundcolour": "#2c3c49" } The PHP file which receives the JSON looks as follows: Code: [Select] <?php $myjson = $_POST['jsonstring']; $jsonchars = json_decode(($myjson), true); $json_errors = array( JSON_ERROR_NONE => 'No error has occurred', JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded', JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded', JSON_ERROR_SYNTAX => 'Syntax error', ); echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL; // do something with the data ?> The problem is the PHP constantly returns the following error: Last error : Syntax error and any attempts to access the JSON data returns NULL values. I have looked at several online examples and cannot see where I might be going wrong, and although users have had problems with syntax errors it normally relates to incorrect JSON. Any advice on this topic would be greatly appeciated Leanne Hallo I'm having a problem inserting $messageorder into mysql datebase. Otherwise works good. So there is no problem with database itself or mysql command too. I suspect there must be something in this code that mysql doesnt like. Also have to say that im able to sent email with $messageorder. Please take a look at the codee. Code: [Select] $messageorder = "\r\n" . 'Order:' . '<br><br><table>' . "\r\n"; $result3 = mysql_query("SELECT * FROM orderslist WHERE supplier='$supplier'") or die(mysql_error()); $data = array(); $data['' . $row3['id']] = $_POST['' . $row3['id']]; while($row3=mysql_fetch_array($result3)) { $value = $_POST['' . $row3['id']]; if ( $value == ""){ } else { $messageorder .= " <tr> <td class='H4'><strong>$row3[name]</strong></td> <td class='H4' align='center'>$value</td> <td class='H4'>$row3[unit]</td> </tr> "; } } $messageorder .= "</table>"; echo $messageorder; date_default_timezone_set('Europe/London'); $supplier=$_GET['order']; $delivery=$_POST['delivery']; $timestamp = date("H:i:s"); $datestamp = date('Y/m/d'); mysql_query ("INSERT INTO orders (id, datestamp, timestamp, supplier, ordertext, delivery ) VALUES ('', '$datestamp', '$timestamp', '$supplier', '$messageorder', '$delivery')"); If someone could help to find a solution I will appriciate ! Thank you very much Hi, it's my first post so hello to you and i hope you will be forgiving:) I've made a basic script, which takes a urls from the form(each of them is the new row) and then search each of those urls for an email. The problem is that only the email from the last url is returned. print_r("show link:". $urls[$i]."<br>"); shows all urls in the form, but the print_r("show current_url:". $current_url); shows only the last one. Code: [Select] <?php $urls = explode("\n", $_POST['urls']); $db = new mysqli('localhost', 'root', 'root', 'urls'); if (mysqli_connect_errno()) { echo 'Błąd: '; exit; } for ($i=0; $i<count($urls); $i++){ print_r("show link:". $urls[$i]."<br>"); $current_url = file_get_contents($urls[$i]); print_r("show current_url:". $current_url); preg_match( "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $current_url, $email);//email print_r ("show email:".$email[0]); $zapytanie = "INSERT INTO urle set adres = '$email[0]' "; $wynik = $db->query($zapytanie); } if ($wynik) { echo $db->affected_rows ."pozycji dodano."; } else { echo mysql_errno() . ":" . mysql_error() . "Wystąpił błąd przy dodawaniu urli "; } $db->close(); ?> My error happens on line #81 For some reason this array will only return 'white'. Is there a problem with the code?
<?php $test = array('blue','green','white'); foreach($test as $val) ?> <?php echo "$val"; ?> I'm sure there must be a way to do whatI am after, as it seems like such an obvious thing to do, but I can't figure it out. 1. I have an array which contains a list of database's and their connections $slaveRes_array[0] = array('server' => 'localhost:3306', 'user' => $u, 'password' => $p, 'database' => 'MySQL01_5083', 'sendmail' => '0', 'repeat' => '0', 'dbID' => '1' ); and so on 10 times I then have a list of MySQL Queries: (at the moment there is only one, but there will be more later on). $query_array[] = array( 'query1' => "SHOW SLAVE STATUS"); The idea is that I take the first database from $slaveRes_array, connect to it, and run each query from the $query_array in turn against that database, and ultimately pass that resultset into an array that I can refer back to later on. Within $slaveRes_array I have a DB name (e.g. MySQL01_5083), I want this to be the first entry in my resultset array, so I can reference this. However, not all database's will return a result. So what I want to end up with is something like: => Array ( [name] => MySQL02_5083 ) ( [Slave_IO_State] => Waiting for master to send event)... (in this case the first server (MySQL01) didn't return a result, so the first item in the array is MySQL02. I have found lots of ways to achieve bits of this, but none that work together. I can get a list of database names that returned a result, but can't get the data to return to the array (or any array). I can get the data into an array, but not the database names. Surely this must be something straight forward that people do all the time, right? My array results keep displaying like this. I want it to just display the numbers in the quotations. any help? Code: [Select] array ( 0 => '4396', ) array ( 0 => '3934', ) array ( 0 => '5063', ) array ( 0 => '4394', ) array ( 0 => '3936', ) array ( 0 => '4393', ) array ( 0 => '4395', ) array ( 0 => '5064', ) array ( 0 => '5062', ) array ( 0 => '4224', ) array ( 0 => '3322', ) array ( 0 => '3321', ) array ( 0 => '3320', ) array ( 0 => '3725', ) I want to store all the hours 0,1,2,3... in my $time array but it returns the last value only and I dont understand why... Code: [Select] <?php $time = array(); $hour = 0; for ( $i=0; $i<=7; $i++ ) { $time['hour'] = $hour; $hour++; } ?> Hello mates, i've been googling about my problem but i couldn't fix it. Code: ###################################### $web = file_get_contents($tmpUrl); $explodedWeb = explode("<b>Somecode:</b> ",$web); print $explodedWeb [1]; ###################################### I'm just printing it for testing purposes, and the $web var works fine(since tried printing the hole source). Error: "Notice: Undefined offset: 1 in ..." I tried to create an empty array in explodedWeb ("$explodedWeb[]") but didn't work either. Greets. Hello All - I have the following array: Code: [Select] array 0 => array 'farmName' => string 'Hallinan' (length=8) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 1 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 2 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 3 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 4 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 5 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 6 => array 'farmName' => string 'Home' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 7 => array 'farmName' => string 'Home' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 8 array 'farmName' => string 'Home' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) The data comes from a flat file that has (as you can see) many of the same names like Home and Holt. Is there a way to extract the first Holt and Home from the array and put those values in a new array? So my new array would look something like: Code: [Select] array 0 => array 'farmName' => string 'Hallinan' (length=8) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 1 => array 'farmName' => string 'Holt' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) 2 => array 'farmName' => string 'Home' (length=4) 'farmInsNum' => string '' (length=0) 'farmFSA' => string '' (length=0) I look through php.net and really couldn't find a function that could handle what I was after. I'm sure I'd have to use a combination of each() and reset() or maybe not? Any help would be very welcome. Thanks! Hello all, I've been working on parsing through some XML data that is formatted as x-schema. It's been a challenge to say the least. I've looked at XMLReader and the like to see if I can parse through the data but with no luck. I found an approach that works but having trouble iterating over the nodes inside the nodes. I'll try to explain: Here's what I have so far. The code produces the following result set: Code: [Select] [4] => Array ( [FARM:NAME] => Array ( [FARM:NAME] => Kenyon Farm [FARM:FARM] => [FARM:TOTALAREA] => 999 [FARM:BUSINESSFIELDS] => [BUSINESSFIELD:FIELD] => [BUSINESSFIELD:LABEL] => K9 [BUSINESSFIELD:TOTALROTATIONS] => 1 [BUSINESSFIELD:TOTALAREA] => 998 [BUSINESSFIELD:FIELDOPTIONS] => [BUSINESSFIELD:FIELD_BOUNDARY] => [BUSINESSFIELD:DATAFILE] => FieldBoundary_2682 [BUSINESSFIELD:ACTIVITIES] => [CUST:FARMS] => ) ) Here's the code that produces that array: Code: [Select] $tuData=file_get_contents("xml/tim.xml"); $simple = $tuData; $p = xml_parser_create(); xml_parse_into_struct($p, $simple, $vals, $index); xml_parser_free($p); $getValue=""; $counter=0; print"<pre>"; print_r($vals); foreach($vals as $data) { if(isset($data['tag'])) { if($data['tag'] == 'FARM:NAME') { $key = $data['tag']; $counter++; } if(trim($key)!== '' && trim($data['tag']) !== '') { $arData[$counter][$key][$data['tag']] = $data['value']; } } } print"<pre>"; print_r($arData); Now to my problem. You'll notice that the array has a key called [BUSINESSFIELD:LABEL] ... in the attached xml file there can be more than one field for each farm. My current solution only gets the first field in the xml file (as the current example shows above) and moves to the next farm and creates a new array of data. I would like to get the other fields for each farm and "stuff" them in the same array. Array's are not my strong suite and would be grateful to anyone that could help me with this problem. Thanks a bunch! |