I use mysqli API to query a large table, every 1000 rows, but the memory of my server grows up very fast. The memory is 0, even the swap. I don't know how to fix it.
The table has 4 million rows so I query the table each time by 1000.
Here is my code:
<?php
ini_set('memory_limit','32M');
$config = require_once('config.php');
$attachmentRoot = $config['attachment_root'];
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
echo "\nRename The Dup Files With Suffix: .es201704111728es \n";
$startTime = microtime(true);
/**
*
* Move dup file to $name + .es201704111728es
*/
$suffix = ".es201704111728es";
$fileLinesLimit = 100000;
$listSuffix = 0;
$lines = 0;
/**
* Create File List.
*/
$fileList = '/tmp/Dupfilelist.txt';
$baseListName = $fileList.$listSuffix;
//$fs = fopen($baseListName,'w');
$totalSize = 0;
$start = 0;
$step = 10000;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
while($result->num_rows > 0)
{
while($result->fetch_row())
{
/*$fiepath = $row[1];
$uniqueIdsArray = array_unique(explode(',',$row[2]));if(empty($row[3]))throw new \Exception("\n".'ERROR:'.$row[0]."\n".var_export($row[3],true)."\n");
$uniqueFilesArray = array_unique(explode(',',$row[3]));
$hasFile = array_search($fiepath,$uniqueFilesArray);
if($hasFile !== false)
unset($uniqueFilesArray[$hasFile]);
$num = count($uniqueIdsArray);
$fileNum = count($uniqueFilesArray);
$ids = implode(',',$uniqueIdsArray);
if($num>1 && $fileNum>0){
//echo "\nID: $row[0] . File Need To Rename:".var_export($uniqueFilesArray,true)."\n";
$size = intval($row[4]);
if($lines >= $fileLinesLimit){
$lines = 0;
$listSuffix++;
//$fileList .= $listSuffix;
}
array_map(function($file) use ($attachmentRoot,$suffix,$fiepath,$totalSize,$size,$fileLinesLimit,&$listSuffix,&$lines,$fileList){
//$fs = fopen($fileList.$listSuffix,'a');
if($file === $fiepath)
return -1;
$source = $file;
$target = $source.$suffix;
//rename($source,$target);
//fwrite($fs,$source.','.$target."\n");
//file_put_contents($fileList.$listSuffix, $source.','.$target."\n",FILE_APPEND);
//$totalSize += intval($size);
$lines ++;
//echo memory_get_usage()."\n";
//fclose($fs);
//unset($fs);
//try to write file without amount memory cost
//$ts = fopen('/tmp/tempfile-0412','w');
},$uniqueFilesArray);
//echo "Test Just One Attachment Record.\n";
//echo "Ids:$ids\n";
//exit();
}*/
}
echo memory_get_peak_usage(true)."\n";
if(!$mysqli->ping())
{
echo "Mysql Conncect Failed.Reconnecting.\n";
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
}
//mysqli_free_result($result);
$result->close();
unset($result);
$start += $step;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
}
echo "Dup File Total Size: $totalSize\n";
echo "Script cost time :".(microtime(true)-$startTime)." ms\n";sleep(1000*10);
mysqli_close($mysqli);
exit();
I enable the XDEBUG extension.Sorry for that.
I disable this extension and everything goes well.
I ran into this issue with PHP Version 7.3.26 on Centos 7. I worked around it by using unbuffered query (instead of buffered). In the above example, replace
$result = $mysqli->query($sql)
with
$result = $mysqli->query($sql, MYSQLI_USE_RESULT)
Related
I keep seeing Waiting for Cache and it takes at least 30 minutes to get
the response.
Is there a better way?
Here's the link:
http://tapnapp.co/planning/phpScripts/getFullViewTasks.php?counter=1&sDateHour=1525154400&eDateHour=1527793200
And here is the code:
<?php
if (isset($_GET['counter'])) {
require_once '../functions.php';
$sDateHour = $_GET['sDateHour'];
$eDateHour = $_GET['eDateHour'];
$now = time() - 24*60*60;
$fn = new Func;
$fn->select('id_profile, groupe','profile',''," date_f_contract>='$now' AND groupe>0");
$sel = new Func;
$getHrName = new Func;
while ($row = mysqli_fetch_assoc($fn->select)) {
$pr_id = $row['id_profile'];
$sel->select('*','counter',''," from_interval>='$sDateHour' AND to_interval<='$eDateHour' AND id_profile='$pr_id'");
$nr= mysqli_num_rows($sel->select);
if ($nr > 0) {
//here we have to do the total counter
$totalCounter = 0;
$from_interval = 0;
$to_interval = 0;
$name = "";
$tmp_id_profile = 0;
$tmp_f_int = 0;
$tmp_to_int = 0;
while ($r = mysqli_fetch_assoc($sel->select)) {
$frint = $r['from_interval'];
$toint = $r['to_interval'];
//$counter_ct = $r['counter'];
$totalCounter += $counter_ct;
$getHrName->select('libelle AS lbl, COUNT(libelle) AS totalHr',"horraire",""," date_heure_deb>='$frint' AND date_heure_fin<='$toint' AND id_profile='$pr_id' GROUP BY libelle ORDER BY totalHr DESC LIMIT 1");
$rr = mysqli_fetch_assoc($getHrName->select);
$r['hrname'] = $rr['lbl'];
$name = $rr['lbl'];
$r['counter'] = $rr['totalHr'];
/*
$from_interval=$frint;
$to_interval = $toint;
*/
$row['tasks'][] = $r;
}
/*
$r['counter']=$totalCounter;
$r['from_interval']=$from_interval;
$r['to_interval']=$to_interval;
$r['hrname']=$name;*/
//$row['tasks'][]=$r;
} else {
/*
id_counter: "1",
id_profile: "17",
from_interval: "1519887600",
to_interval: "1519934400",
counter: "18"}
*/
/*
$fake['id_counter']=0;
$fake['id_profile']=$pr_id;
$fake['from_interval']=$sDateHour;
$fake['to_interval']=$eDateHour;
$fake['counter']=0;
$row['tasks'][]=$fake;
*/
}
$res[] = $row;
}
$temp['data'] = $res;
$fn->deconnect();
$sel->deconnect();
echo json_encode($temp, JSON_PRETTY_PRINT);
}
?>
So what is wrong with this if anyone can understand?
Is that because of mysql or because of the php?
I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.
I'm attempting to create a PHP script that will create a random code and check it against a database to see if it exists. I'd like it to check that if it exists then generate another createRandomCode() and check it.
Unsure how to proceed with looping until the number of rows are 0.
function createRandomCode($length='6'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
$shorturl = createRandomCode();
$q = $db - > query("SELECT * FROM maps WHERE url='".$shorturl.
"'");
if (mysqli_num_rows($q) > 0) {
$arr = json_encode($arr);
echo $arr;
}
Sounds like a good candidate for a do...while loop:
do {
$shorturl = createRandomCode();
$q = $db->query("SELECT * FROM maps WHERE url='".$shorturl."'");
} while(mysqli_num_rows($q) > 0);
function regenerateCode(){
global $connection;
do{
$serial2 = rand(0,7);
$check_code = "SELECT * FROM `voters` WHERE `serial` = '$serial2'";
$run_check_code = mysqli_query($connection,$check_code);
$count = mysqli_num_rows($run_check_code);
} while( $count > 0 );
return $serial2;
}
I'm currently experiencing issues where array_push() is not working. I have ensured the arrays are directly accessible and declared correctly. Yet I'm still receiving these warnings and the values are not being pushed onto the array.
Here is my code:
include('../connstr.inc');
$email=$_REQUEST["email"];
$datafile=$_REQUEST["datafile"];
$email_safe=preg_replace("/[^a-zA-Z]/","_",$email);
$path="../uploaded_data";
$xml = simplexml_load_file("{$path}/{$email_safe}/{$datafile}.xml");
// Retreive data details for specified activity
$lapCount = $xml->Activities->Activity->Lap->count();
// Lap Variables
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
$avgSpeed = array();
// Convert filename to DateTime format
$datafile = convertID($datafile);
$datafile = date('Y-m-d H:i:s', strtotime($datafile));
// Variables for accurate distance calculations
$polarDistance = true;
$lapID;
$totalLapDistance;
$firstPoint = array();
$secondPoint = array();
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
$totalLapDistance = 0;
$lapNumber = $x+1;
$totalTime[$x] = $xml->Activities->Activity->Lap[$x]->TotalTimeSeconds;
$distance[$x] = $xml->Activities->Activity->Lap[$x]->DistanceMeters;
$maxSpeed[$x] = $xml->Activities->Activity->Lap[$x]->MaximumSpeed;
$calories[$x] = $xml->Activities->Activity->Lap[$x]->Calories;
$intensity[$x] = $xml->Activities->Activity->Lap[$x]->Intensity;
$trigMethod[$x] = $xml->Activities->Activity->Lap[$x]->TriggerMethod;
$avgSpeed[$x] = $xml->Activities->Activity->Lap[$x]->Extensions->LX->AvgSpeed;
// Store activity details into the 'detail' table
$sqlLap = "INSERT INTO lap (lapDate,lapNumber,TotalTime,distance,maxSpeed,avgSpeed,calories,intensity,trigMethod) VALUES (\"$datafile\",\"$lapNumber\",\"$totalTime[$x]\",\"$distance[$x]\",\"$maxSpeed[$x]\",\"$avgSpeed[$x]\",\"$calories[$x]\",\"$intensity[$x]\",\"$trigMethod[$x]\")";
$runLap = mysql_query($sqlLap) or die("unable to complete INSERT action:$sql:".mysql_error());
// Trackpoint variables
$altitude = array(); $tDistance = array(); $latitude = array();
$longitude = array(); $speed = array(); $pointTime = array();
// Retreive lapID
$lapID = getLapID();
// Find how many tracks exist for specified lap
$trackCount = $xml->Activities->Activity->Lap[$x]->Track->count();
$trackpointTotalCount = 1;
for($t = 0; $t < $trackCount; $t++) {
// Find out how many trackpoints exist for each track
$trackpointCount = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint->count();
// Collect details for each specificied track point
for($tp = 0; $tp < $trackpointCount; $tp++) {
$altitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->AltitudeMeters;
$tDistance[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->DistanceMeters;
$pointTime[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Time;
$latitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LatitudeDegrees;
$longitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LongitudeDegrees;
$speed[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Extensions->TPX->Speed;
// Check Track point
if(checkTP($altitude[$tp], $tDistance[$tp], $latitude[$tp], $longitude[$tp], $speed[$tp])) {
// Check if accurate distance should be calculated
if($polarDistance) {
$aa = $latitude[$tp];
$bb = $longitude[$tp];
$cc = $altitude[$tp];
if($tp == 0) {
array_push($firstPoint, $aa, $bb, $cc);
} else if($tp != 0) {
array_push($secondPoint, $aa, $bb, $cc);
}
printArray($firstPoint);
printArray($secondPoint);
// Add distance between trackpoints to total lap distance
$totalLapDistance += calcDistance($firstPoint, $secondPoint);
}
// Insert current trackpoint data into 'trackpoint' table
$sqlTC = "INSERT INTO trackpoint (tpDate,tpNumber,altitude,distance,latitude,longitude,speed,pointTime) VALUES (\"$datafile\",\"$trackpointTotalCount\",\"$altitude[$tp]\",\"$tDistance[$tp]\",\"$latitude[$tp]\",\"$longitude[$tp]\",\"$speed[$tp]\",\"$pointTime[$tp]\")";
$runTC = mysql_query($sqlTC) or die("unable to complete INSERT action:$sql:".mysql_error());
}
$trackpointTotalCount++;
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
}
}
if($polarDistance) {
if($tp != 0) {
// Update lap with more accurate distance
echo $totalLapDistance . '<br />';
$sqlUlap = "UPDATE lap SET accDistance='$totalLapDistance' WHERE lapID = '$lapID' ";
$runUlap = mysql_query($sqlUlap) or die("unable to complete UPDATE action:$sql:".mysql_error());
}
}
}
I didn't include all of the code below as there is quite a lot and I very much doubt it's relevant.
The warnings themselves only appear when trying to push a variable onto $secondPoint:
array_push($secondPoint, $aa, $bb, $cc);
However values are not being pushed onto either of the variables ($firstPoint, $secondPoint)
As a test I did echo $aa,bb and $cc and they did contain correct values.
Anybody have an idea of what I'm doing wrong?
EDIT: I have showed more of the code as I do use these arrays later, however this should not affect how the values are initially pushed? Below is some code which may affect it, namely the assign by reference?
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
That unset($secondPoint) will probably do it.
Try this instead:
if($polarDistance) {
if($tp != 0) {
$firstPoint = $secondPoint;
$secondPoint = array();
}
}
Ok Edit here still got an issue but not the same as before updated code
<?php
date_default_timezone_set('Europe/London');
$date = date('Y-m-d H:i:s', time());
$now = date('Y-m-d H:i:s');
$dbhost = "localhost";
$dbuser = "admin_cdm_clap";
$dbpass = "zdqUyFc5bAG1e6TWrIhijH3j7gB8xhmHI4q";
$db = "iTunesConnect";
$driveID = 562220229;
$connect = mysql_connect($dbhost,$dbuser,$dbpass) or die (mysql_error());
mysql_select_db($db);
$query = "SELECT `code` from `countries`";
$result = mysql_query($query) or die (mysql_error());
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
$country=mysql_result($result,$i,"code");
$completeUrl = "https://itunes.apple.com/".strtolower($country)."/rss/toppaidapplications/limit=300/genre=6002/xml";
//echo $completeUrl.'<br>';
$xml = simplexml_load_file($completeUrl);
$entries = $xml->entry;
for ($a = 0; $a < 300; $a++) {
//$updated = $entries[$a]->updated;
$id = $entries[$a]->id->attributes('im', true)->id;
$bundle = $entries[$a]->id->attributes('im', true)->bundleId;
$cc = $entries[$a]->id;
$title = $entries[$a]->title;
$category = $entries[$a]->category['term'];
$nUpdated = microtime(true); //strtotime(substr($updated,0,10).' '.substr($updated, 11, 8))
$storeCode = substr($cc, 25, 2);
$storeCat = 6002;
if($id == $driveID){
$rankRec = "INSERT INTO rankings (id, rank, updated, store, category) VALUES (NULL, $a, $nUpdated, '$storeCode','$storeCat')";
mysql_query($rankRec) or die(mysql_error());
} else {
error_reporting(E_ALL);
ini_set('display_errors', '1');
}
}
$i++;
}
?>
I am now getting the following errror;
Notice: Trying to get property of non-object in /var/www/vhosts/createdm.com/httpdocs/iTunesConnect/iTunesRanking.php on line 24
Fatal error: Call to a member function attributes() on a non-object in /var/www/vhosts/createdm.com/httpdocs/iTunesConnect/iTunesRanking.php on line 24
The error is here
$id = $entries[$a]->id->attributes('im', true)->id;
and it says that the attributes function is called on a non-object, which tells us that the ->id is not an object; it is probably unset.
So this in turn tells us that either the XML has an entry without a proper id, or that simplexml_load_file think there is.
I'd strenghten the checks on the objects:
// This will save the current XML to a file, so that we may check
// the EXACT data we got, instead of requesting it again and, who
// knows?, get an intact copy, or a different version altogether
$dat = file_get_contents($completeUrl);
$fp = fopen('temp.xml', 'w');
fwrite($fp, $dat);
fclose($fp);
$xml = simplexml_load_file('temp.xml');
// Then...
$entries = $xml->entry;
for ($a = 0; $a < 300; $a++) {
if (!isset($entries[$a]))
die("Entries $a-300 were not found");
// if you discover that some small country has not 300 entries,
// then: (a) reactivate the error reporting which should have warned you,
// (b) replace the 300 with count($entries), or the for with a foreach loop.
// Moved $cc= here, it's more efficient.
$cc = $entries[$a]->id;
if (!is_object($cc))
die("Check entry $a's 'id' in temp.xml");
$id = $cc->attributes('im', true)->id;
$bundle = $cc->attributes('im', true)->bundleId;
// $cc = $entries[$a]->id;
$title = $entries[$a]->title;