I want to store an property->object name in a table and access in code.
What is the proper way to accomplish the following.
$patient = new stdClass();
$patient->patient_number = '12345';
$cls = 'patient';
$prp = 'patient_number';
echo 'test1 = ' . $patient->patient_number . '<br>';
//--- this prints 12345 as expected;
echo 'test2 = ' . $$cls->patient_number . '<br>';
//--- this print 12345 as expected;
echo 'test3 = ' . $$cls->${$prp} . '<br>';
//--- this generates undefined variable patient_number;
Use this:
echo 'test3 = ' . ${$cls}->{$prp} . '<br>';
I'm trying to use Simple_Html_Dom parser to parse a web page for NBA statistics. I'm going to have a lot of different urls, but parsing the same data, so I figured I would create a function. Outside of the function, this parser works great, however as soon as I place the parsing inside the function, I receive a connection error. Just wondering, if anyone knows why I can't run the file_get_html inside the function. Here is the code below. Please help!
include('simple_html_dom.php');
$nbaPlayers = 'playerstats/15/1/eff/1-2';
function nbaStats($url){
$html = 'http://www.hoopsstats.com/basketball/fantasy/nba/';
$getHtml = $html . $url;
$a = file_get_html("$getHtml");
foreach($a->find('.statscontent tbody tr') as $tr){
$nbaStatLine = $tr->find('td');
$nbaName = $nbaStatLine[1]->plaintext;
$nbaGamesPlayed = $nbaStatLine[2]->plaintext;
$nbaMinuesPlayed = $nbaStatLine[3]->plaintext;
$nbaTotalPoints = $nbaStatLine[4]->plaintext;
$nbaRebounds = $nbaStatLine[5]->plaintext;
$nbaAssists = $nbaStatLine[6]->plaintext;
$nbaSteals = $nbaStatLine[7]->plaintext;
$nbaBlocks = $nbaStatLine[8]->plaintext;
$nbaTurnovers = $nbaStatLine[9]->plaintext;
$nbaoRebounds = $nbaStatLine[11];
$nbadRebounds = $nbaStatLine[12];
$nbaFieldGoals = $nbaStatLine[13];
$nbaFieldGoals = explode("-", $nbaFieldGoals);
$nbaFieldGoalsMade = $nbaFieldGoals[0];
$nbaFieldGoalsAttempted = $nbaFieldGoals[1];
// Player Stat Line
$playerStats = $nbaName . ': gp - ' . $nbaGamesPlayed . ' mp - ' . $nbaMinutesPlayed . ' pts - ' . $nbaTotalPoints . ' rb - ' . $nbaRebounds . ' as - ' . $nbaAssists . ' s - ' . $nbaSteals . ' bl - ' . $nbaBlocks . ' to - ' . $nbaTurnovers;
echo $playerStats . '<br /><br />';
}
}
nbaStats($nbaPlayers);
When passing a variable to a function you don't need to wrap the variable in quotations. Quotations are used when passing text directly to a function or assigning text to a variable.
Change this:
$a = file_get_html("$getHtml");
To this:
$a = file_get_html($getHtml);
I am trying to parse a simple response from the server and use its values.
I was able to get the required information as follows:
The actual response :
AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success
What I need is separate values for :
AccountID
Authenticated
ResponseCode
ResponseText
My code so far :
$tempValue = explode("\n", $response);
foreach($tempValue as $row => $data)
{
//get row data
$row_data = explode('&', $data);
$row_internal = explode('=', $row_data);
$info2[$row]['id'] = $row_internal[0];
$info2[$row]['name'] = $row_internal[1];
$info2[$row]['description'] = $row_internal[2];
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
echo 'Account ID: ' . $info[$row]['id'] . '<br />';
echo 'Authenticated: ' . $info[$row]['name'] . '<br />';
echo 'Response Code: ' . $info[$row]['description'] . '<br />';
echo '<br></br>';
echo 'Account ID: ' . $info2[$row]['id'] . '<br />';
echo 'Authenticated: ' . $info2[$row]['name'] . '<br />';
echo 'Response Code: ' . $info2[$row]['description'] . '<br />';
}
Result for the above code :
Account ID: AccountID=0
Authenticated: Authenticated=1
Response Code: ResponseCode=0
Account ID:
Authenticated:
Response Code:
What I needed was just the values for the fields like :
Account ID: 0
Authenticated: 1
Response Code: 0
If this is a query string response, then no need to explode, there is a better tool that handles this well.
Just use parse_str().
Simple one line response example:
$response = 'AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success';
parse_str($response, $data);
echo '<pre>';
print_r($data);
Or if the response looks like a multiline string like this, you could apply it like:
$response = "AccountID=1&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=2&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=3&Authenticated=1&ResponseCode=0&ResponseText=Success
";
$responses = explode("\n", $response);
foreach ($responses as $key => $value) {
parse_str($value, $data);
if(!empty($data)) {
echo 'Account ID: '.$data['AccountID'] .'<br/>';
echo 'Authenticated: '.$data['Authenticated'] .'<br/>';
echo 'Response Code: '.$data['ResponseCode'] .'<br/>';
echo 'Response Text: '.$data['ResponseText'] .'<br/>';
echo '<br/>';
}
}
I am trying to use $value inside the $feed_title variable. And generate all 200 $feed_title variables.
What I am trying to accomplish would look like this:
Feed Url: http://something.com/term/###/feed
Feed Title: Some Title
Where the ### varies from 100-300.
I am using the following code, and getting the urls, but not sure how to get the titles for each feed:
$arr = range(100,300);
foreach($arr as $key=>$value)
{
unset($arr[$key + 1]);
$feed_title = simplexml_load_file('http://www.something.com/term/'
. ??? . '/0/feed');
echo 'Feed URL: <a href="http://www.something.com/term/' . $value
. '/0/feed">http://www.something.com//term/' . $value
. '/0/feed</a><br/> Feed Category: ' . $feed_title->channel[0]->title
. '<br/>';
}
Do I need another loop inside of the foreach? Any help is appreciated.
If you want to get the title of a page, use this function:
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Here's some sample code:
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
$arr = range(300,305);
foreach($arr as $value)
{
$feed_title = getTitle('http://www.translate.com/portuguese/feed/' . $value);
echo 'Feed URL: http://www.translate.com/portuguese/feed/' . $value . '<br/>
Feed Category: ' . $feed_title . '<br/>';
}
?>
This gets the title from translate.com pages. I just limited the number of pages for faster execution.
Just change the getTitle to your function if you want to get the title from xml.
Instead of using an array created with range, use a for loop as follows:
for($i = 100; $i <= 300; $i++){
$feed = simplexml_load_file('http://www.something.com/term/' . $i . '/0/feed');
echo 'Feed URL: http://www.something.com/term/' . $i . '/0/feed/ <br /> Feed category: ' . $feed->channel[0]->title . '<br/>';
}
I'm new to PHP and am trying to parse certain text from a txt file, and then insert the text into a MySQL database. So, let's get more specific. The file's format is as such, and it is repeated through the document end. the ellipses represent the previous and next tones.
...
[Tone27]
Atone = 707.3
Btone = 746.8
Btonelength = 3
Btonedebounce = 1
Description = Fire Department 1
mp3_Emails = email#address.com,email2#address.com,email3#address.com
amr_Emails = email2#textmessaging.com,email1#textmessaging.com
alert_command = c:\test.bat
post_email_command = c:\test2.bat
radio_frequency = 154.475
exclude_from = 13:25
exclude_to = 13:35
exclude_emails = email2#textmessaging.com,email2#address.com
...
What I want to do is parse the first items(e.g. '[tone27]') in each "tone block" from the file and insert it into the first field of a NEW row in the db. I then need to evaluate what comes before each line's " = ", for instance "Atone," and insert what comes after that line's " = ", for instance "707.3" into a field by that name. so, this row may look like this in the db:
$id | [tone27] | 707.3 |746.8 | 3 | 1 | Fire Department 1 |email1#x.com,email2#x.com,e...|...
and so on...
i've been able to isolate each thing by performing string functions, but am unsure of how to set up a loop that would insert each value properly. Here's the code I used to isolate them, but it's not helping at all with actually getting them into the database.
$txt_file = file_get_contents('config/tones.txt');
$rows = explode("\n", $txt_file);
foreach($rows as $row => $data)
{
$row_data = explode(' = ', $data);
if ((isset($row_data[0])) && ($row_data[0] !== " " )){
$info[$row]['attribute'] = $row_data[0];
$info_attribute = trim($info[$row]['attribute']);
}
if (isset($row_data[1])){
$info[$row]['value'] = $row_data[1];
$info_value = trim($info[$row]['value']);
//display data
echo 'Row ' . $row . ' Attribute: ' . $info_attribute . '<br />';
echo 'Row ' . $row . ' Value: ' . $info_value . '<br />';
} elseif (($info[$row]['attribute']) && (!empty($info_attribute))) {
echo "<br>";
echo 'Row ' . $row . ' Attribute: ' . $info_attribute . '<br />';
continue;
}
I'M A NOOB, NO DOUBT. I'M LOST. Thanks in advance for your help!!!
****|| EDIT ||****
Thanks for all of the excellent answers! here's what I've resultingly come up with. No queries yet, just a simple dash of the read portion of CRUD, but the code will be the same, only with queries. A big thanks to #leepowers for introducing me to the wonderful parse_ini_file() function.
foreach(parse_ini_file("config/tones.txt", true) as $k => $v){
extract($v, EXTR_SKIP);
echo "<br>";
echo $k . "<br>";
foreach($v as $sv => $ssv){
$lcase_sv = strtolower($sv);
if (trim($lcase_sv) == 'amr_emails'){
echo "sv: amr_Emails:<br>";
echo "ssv:<br>";
$eA = explode(',', trim($ssv));
foreach($eA as $eK => $eV){
echo "email" . filter_var($eK + 1, FILTER_SANITIZE_NUMBER_INT) . ": " . $eV . "<br>";
}
} elseif (trim($lcase_sv) == 'mp3_emails'){
echo "ssv:<br>";
$eA = explode(',', trim($ssv));
foreach($eA as $eK => $eV){
echo "email" . filter_var($eK + 1, FILTER_SANITIZE_NUMBER_INT) . ": " . $eV . "<br>";
}
}else {
echo "sv: " . $sv .", " . "s: " . $ssv . "<br>";
}
}
}
Use parse_ini_file to load the data structure into an array.
From there you can build and execute SQL statements:
$entries = parse_ini_file("config/tones.txt", true);
foreach ($entries as $section => $fields) {
extract($fields, EXTR_SKIP);
$sql = "INSERT INTO mytable (section, atone, btone) VALUES ($section, '$Atone', '$Btone'";
....
}
Of course, you'll need to prepare and escape the SQL statement before executing it.
parse_ini_file($source); return an associative array
$query = 'INSET INTO ... (key, value) VALUES (:key, :value)';
$stmt = DB::prepare($query);
foreach( parse_ini_file($source) as $key => $value )
{
$stmt->execute(array(':key' => $key, ':source' => $source));
}
This example use PDO
Just output of file in loop is:
foreach( parse_ini_file($source) as $key => $value )
{
echo $key; // Atone in first loop
echo $value; //707.3 in first loop
// BUT NOT USE THIS!!! use mysqli or PDO
mysql_query("INSERT INTO ... (key, value) VALUES ($key, $value)");
}
Here's another way to do it. Just need to modify it according to you needs (number of rows/credentials). It's better to use PDO.
$username = 'yourusername';
$password = 'yourpass';
try {
$conn = new PDO('mysql:host=127.0.0.1;dbname=yourdbname', $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'successfully connected';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
foreach(parse_ini_file('yourfile.ini', true) as $row)
{
try {
// just adjust the number of columns accordingly
$stmt = $conn->prepare('insert into tablename values(?,?,?,?,?,?,?,?,?,?,?,?,?)');
// $row contains the values to insert
$stmt->execute($row);
echo 'rows affected' . $stmt->rowCount(); // 1
}catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}