I'm working on my PHP to get the list of time. I'm using DomDocument to get the time, I want to find a way to reduce the code as I have got the 69 tags of time in my get-listing.php script.
if I use this:
$time1 = $xpath->query("*/span[#id='time1']");
$time2 = $xpath->query("*/span[#id='time2']");
$time3 = $xpath->query("*/span[#id='time3']");
$time4 = $xpath->query("*/span[#id='time4']");
$time5 = $xpath->query("*/span[#id='time5']");
$time6 = $xpath->query("*/span[#id='time6']");
$time7 = $xpath->query("*/span[#id='time7']");
...etc until to get time69
$time69 = $xpath->query("*/span[#id='time69']");
It will be too large for me to write the list of code to parsing the time from the time1 tag to time69 tag.
<?php
ini_set('max_execution_time', 300);
$errmsg_arr = array();
$errflag = false;
function getState($string)
{
$ex = explode(" ",$string);
return $ex[1];
}
$xml .= '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '
<tv generator-info-name="www.mysite.com/xmltv">';
$baseUrl = file_get_contents('http://www.mysite.com/get-listing.php');
$domdoc = new DOMDocument();
$domdoc->strictErrorChecking = false;
$domdoc->recover=true;
//#$domdoc->loadHTMLFile($baseUrl);
#$domdoc->loadHTML($baseUrl);
$links = $domdoc->getElementsByTagName('a');
$i = 0;
$count = 0;
$data = array();
foreach($links as $link)
{
//echo $domdoc->saveXML($link);
if($link->getAttribute('href'))
{
if(!$link->hasAttribute('id') || $link->getAttribute('id')!='streams')
{
$url = str_replace("rtmp://", "", $link->getAttribute('href'));
$url = str_replace(" ", "%20", $link->getAttribute('href'));
//echo $url;
//echo "<br>";
$sdoc = new DOMDocument();
$sdoc->strictErrorChecking = false;
$sdoc->recover=true;
#$sdoc->loadHTMLFile($url);
$time1_span = $sdoc->getElementById('time1');
//$spans = $sdoc->getElementsByTagName('time1');
$query = parse_url($url)['query'];
$channel_split = explode("&", $query)[0];
$channel = urldecode(explode("=",$channel_split)[1]);
$id_split = explode("&", $query)[1];
$my_id = urldecode(explode("=",$id_split)[1]);
$xpath = new DOMXpath($sdoc);
$time1 = $xpath->query("*/span[#id='time1']");
$time2 = $xpath->query("*/span[#id='time2']");
$time3 = $xpath->query("*/span[#id='time3']");
//$time4 = $xpath->query("*/span[#id='time4']");
$array = array(
$time1,$time2,$time3
);
// Save the output format
$DATE_FORMAT_STRING = "YmdHis";
// GET the current STAGE
$current_state = getState($array[0]->nodeValue);
$offset = 0;
$flag = 0;
foreach($array as $time)
{
echo $time->item(0)->nodeValue;
// Get the item state.
//$this_state = getState($time);
$this_state = getState($time->item(0)->nodeValue);
//echo $time->nodeValue;
// check if we past a day?
if($current_state == "PM" && $this_state == "AM")
{
$offset++;
}
$this_unix = strtotime($time->item(0)->nodeValue) + (60 * 60 * 24 * $offset);
$values[] = date($DATE_FORMAT_STRING, $this_unix);
//echo date($DATE_FORMAT_STRING, $this_unix);
echo $values[$count];
echo "<br></br>";
$starttime = $times->nodeValue;
//echo $starttime;
echo "<programme channel='".$my_id." ".$channel." start='".$starttime."' stop='".$stoptime."'>";
/*if($flag>0)
{
//echo "<programme channel='".$my_id." ".$channel." start='".$starttime."' stop='".$stoptime."'>";
$stoptime = $starttime;
$flag=1;
}
else
{
$stoptime = $starttime;
}*/
$current_state = $this_state;
$count++;
}
}
}
}
?>
My question is how do you write the simple way to write the code to make it shorter to get the element id of time1 to time69 using with few line of code?
Edit: I'm getting fatal error when I'm trying to print the list of strings.
The error are jumping on this line:
$time{$i} = $xpath->query("*/span[#id='time".$i."']");
It could be this:
echo $time->item(0)->nodeValue;
Fatal error: Cannot use object of type DOMNodeList as array in /home/myusername/public_html/work_on_this.php on line 57
Here is the update code:
for ($i = 1; $i < 70; $i++)
{
$time{$i} = $xpath->query("*/span[#id='time".$i."']");
$array = array(
$time{$i}
);
foreach($array as $time)
{
echo $time->item(0)->nodeValue;
}
}
Update the code to following,
$time_arr = array();
for ($i = 1; $i < 70; $i++){
$time_arr[] = $xpath->query("*/span[#id='time".$i."']");
}
foreach($time_arr as $time){
echo $time->item(0)->nodeValue;
}
I'm adding the values to an array directly in the for loop instead of assigning them separately.
And also foreach should not be within for loop which gets the time value.
Use a for loop:
for ($i = 1; $i < 70; $i++) {
$time{$i} = $xpath->query("*/span[#id = \"time\" . $i]");
}
Related
$now = time();
$day7 = array();
$day7_srt="";
//get last 7days
for($i=0; $i<7; $i++){
$d = mktime(0,0,0,date('m',$now),date('d',$now)-$i);
$day7[$i]["d"] = date('d',$d);
$day7[$i]["m"] = date('m',$d);
$day7[$i]["y"] = date('Y',$d);
$day7[$i]["date"] = date('Y-m-d',$d);
}
sort($day7);
foreach ($day7 as $key => $value) {
$d = $value['d'];
$m = $value['m'];
$day7_srt .= "\"$m-$d\",";
}
$day7_srt=substr("$day7_srt",0,-1);
echo $day7_srt;
I need get the last 7 days text.
if not sort($day7), I will get.
"12-02","12-01","11-30","11-29","11-28","11-27","11-26"
if use sort($day7)
"12-01","12-02","11-26","11-27","11-28","11-29","11-30"
But I need
"11-26","11-27","11-28","11-29","11-30","12-01","12-02"
<?php
$now = time();
$day7 = array();
$day7_srt="";
//get last 7days
for($i=0; $i<7; $i++){
$d = mktime(0,0,0,date('m',$now),date('d',$now)-$i);
$day7[$i]["d"] = date('d',$d);
$day7[$i]["m"] = date('m',$d);
$day7[$i]["y"] = date('Y',$d);
$day7[$i]["date"] = date('Y-m-d',$d);
}
asort($day7);
foreach ($day7 as $key => $value) {
$d = $value['d'];
$m = $value['m'];
$day7_srt .= "\"$m-$d\",";
}
$day7_srt=substr("$day7_srt",0,-1);
$array = explode(",",$day7_srt);
sort($array);
$day7_srt = implode(",",$array);
echo $day7_srt;
?>
o/p
"11-26","11-27","11-28","11-29","11-30","12-01","12-02"
I want to create an array from an input string. Before this code, I've tried explode, but the array remains length 1. Each string that I've tried is still one in array[0]. Here's my code so far:
public function word()
{
$kata = array($this->kal->getHasil());
if (!empty($kata)) {
$n = count($kata)
for ($i = 0; $i < $n; $i++) {
$imin = $i;
for ($j = $i; $j < $n; $j++) {
if ($kata[$j] < $kata[$imin]) {
$imin = $j;
}
}
$temp = $kata[$i];
$kata[$i] = $kata[$imin];
$kata[$imin] = $temp;
}
for ($i = 0; $i < $n; $i++) {
echo "$kata[$i] ";
}
}
}
public function tokenize()
{
$temp = $this->kal->getHasil();
$token = explode(" ", $temp);
return $token;
}
$hasil = $pp->tokenize();
for ($i = 0; $i < sizeof($hasil); $i++) {
$st = new stemming();
$hasil[$i] = $pp->singkatan($hasil[$i]);
$hasil[$i] = $st->stem($hasil[$i]);
$hasil[$i] = $pp->stopWord($hasil[$i]);
//echo "$hasil[$i] ";
$hb = new hitungBobot($hasil[$i]);
$hb->word();
}
How would I fix this?
You can use a globar var, see the code:
public function word(){ $kata = array($this->kal->getHasil());
global $output;
if(!empty($kata)){
$ar= count($kata)
$output += $ar;
}
public function tokenize() {
$temp = $this->kal->getHasil();
$token = explode(" ",$temp);
return $token;
}
$output = 0;
$hasil = $pp->tokenize();
for($i=0; $i<sizeof($hasil); $i++) {
$st = new stemming();
$hasil[$i] = $pp->singkatan($hasil[$i]);
$hasil[$i] = $st->stem($hasil[$i]);
$hasil[$i] = $pp->stopWord($hasil[$i]);
//echo "$hasil[$i] ";
$hb = new hitungBobot($hasil[$i]);
$hb->word();
}
echo $output;
I extract values from an XML with PHP
<?php
$url = 'list.xml';
$xml = simplexml_load_file($url);
$entries = $xml->item;
$i = 0;
$total = 1;
foreach($entries as $entry){
$i++;
$number[$i] = $entry->total;
$total *= $number[$i];
}
echo $total;
?>
How can I build a total based on each $number extracted from the XML? Right now, my total is zero.
So for all loops together something like:
$total = $number[1] * $number[2] * $number[3] * $number[4] ....
This should work for you:
(You have to cast the return of simplexml_load_file() to double)
$url = "list.xml";
$xml = simplexml_load_file($url);
$entries = $xml->results->rate;
$count = 0;
$total = 1;
$number = array();
foreach($entries as $entry){
$count++;
$number[$count] = $entry->Bid;
$total *= (double)$number[$count];
}
echo "Total: " . $total;
I have an RSS xml file that is pretty large, with more than 700 nodes.
I am using XMLReader Iterator library to parse it and display the results as 10 per page.
This is my sample code for parsing xml:
<?php
require('xmlreader-iterators.php');
$xmlFile = 'http://www.example.com/rss.xml';
$reader = new XMLReader();
$reader->open($xmlFile);
$itemIterator = new XMLElementIterator($reader, 'item');
$items = array();
foreach ($itemIterator as $item) {
$xml = $item->asSimpleXML();
$items[] = array(
'title' => (string)$xml->title,
'link' => (string)$xml->link
);
}
// Logic for displaying the array values, based on the current page.
// page = 1 means $items[0] to $items[9]
for($i = 0; $i <= 9; $i++)
{
echo ''.$items[$i]['title'].'<br>';
}
?>
But the problem is that, for every page, i am parsing the entire xml file and then just displaying the corresponding page results, like: if the page is 1, displaying the 1 to 10 nodes, and if the page is 5, displaying 41 to 50 nodes.
It is causing delay in displaying data. Is it possible to read just the nodes corresponding to the requested page? So for the first page, i can read nodes from 1 to 10 positions, instead of parsing all the xml file and then display first 10 nodes. In other words, can i apply a limit while parsing an xml file?
I came across this answer of Gordon that addresses a similar question, but it is using SimpleXML, which is not recommended for parsing large xml files.
use array_splice to extract the portion of array
require ('xmlreader-iterators.php');
$xmlFile = 'http://www.example.com/rss.xml';
$reader = new XMLReader();
$reader->open($xmlFile);
$itemIterator = new XMLElementIterator($reader, 'item');
$items = array();
$curr_page = (0 === (int) $_GET['page']) ? 1 : $_GET['page'];
$pages = 0;
$max = 10;
foreach ($itemIterator as $item) {
$xml = $item->asSimpleXML();
$items[] = array(
'title' => (string) $xml->title,
'link' => (string) $xml->link
);
}
// Take the length of the array
$len = count($items);
// Get the number of pages
$pages = ceil($len / $max);
// Calculate the starting point
$start = ceil(($curr_page - 1) * $max);
// return the portion of results
$arrayItem = array_slice($items, $start, $max);
for ($i = 0; $i <= 9; $i ++) {
echo '' . $arrayItem[$i]['title'] . '<br>';
}
// pagining stuff
for ($i = 1; $i <= $pages; $i ++) {
if ($i === (int) $page) {
// current page
$str[] = sprintf('<span style="color:red">%d</span>', $i);
} else {
$str[] = sprintf('%d', $i, $i);
}
}
echo implode('', $str);
Use cache in this case, since you cannot parse partially an XML.
Check this
<?php
if($_GET['page']!=""){
$startPagenew = $_GET['page'];
$startPage = $startPagenew-1;
}
else{
$startPage = 0;
}
$perPage = 10;
$currentRecord = 0;
$xml = new SimpleXMLElement('http://sports.yahoo.com/mlb/teams/bos/rss.xml', 0, true);
echo $startPage * $perPage;
foreach($xml->channel->item as $key => $value)
{
$currentRecord += 1;
if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)){
echo "$value->title";
echo "<br>";
}
}
//and the pagination:
//echo $currentRecord;
for ($i = 1; $i <= ($currentRecord / $perPage); $i++) {
echo("<a href='xmlpagination.php?page=".$i."'>".$i."</a>");
} ?>
Updated
Check this Link
http://www.phpclasses.org/package/5667-PHP-Parse-XML-documents-and-return-arrays-of-elements.html
You can use Dom and Xpath. It should be much faster, since Xpath allows you to select nodes by their position in a list.
<?php
$string = file_get_contents("http://oar.icrisat.org/cgi/exportview/subjects/s1=2E2/RSS2/s1=2E2.xml");
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($string);
$string = "";
$xpath = new DOMXPath($dom);
$channel = $dom->getElementsByTagName('channel')->item(0);
$numItems = $xpath->evaluate("count(item)", $channel);
// get your paging logic
$start = 10;
$end = 20;
$items = $xpath->evaluate("item[position() >= $start and not(position() > $end)]", $channel);
$count = $start;
foreach($items as $item) {
print_r("\r\n_____Node number $count ");
print_r( $item->nodeName);
$childNodes = $item->childNodes;
foreach($childNodes as $childNode) {
print_r($childNode->nodeValue);
}
$count ++;
}
I want to show on first page randomly selected links from a dati.txt file (from about 1000 links 5 randomly selected) from this:
<?php
$righe_msg = file("dati.txt");
$numero=0;
foreach($righe_msg as $riga)
{
$dato = explode("|", trim($riga));
if (trim($dato[5])=="yes")
{
$numero++;
echo"<tr><td bgcolor='#EEEEEE'>» <a href='$dato[2]'> $dato[1]</a></td></tr> ";
}
}
?>
About dati.txt
dati.txt is made like this
date1.. |title1..|link1...|description1|email1|yes
date2.. |title2..|link2...|description2|email2|yes
date3.. |title3..|link3...|description3|email3|yes
date4.. |title4..|link4...|description4|email4|yes
date5.. |title5..|link5...|description5|email5|yes
date6.. |title6..|link6...|description6|email6|yes
..
But how do you get for example (links) out with this code:
$links = file("dati.txt");
$numLinks = count($links);
$tmp = array();
for ($i = 0; $i < min(5, $numLinks); $i++)
{
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
// Avoid duplicates:
if (in_array($randomLink, $tmp))
{
$i--;
continue;
}
$tmp[] = $randomLink;
echo $randomLink;
}
Thanks
<?php
$links = file('links.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// used this for testing (generated from a file with one link each line (+carriage return)
//$links = ARRAY('foo 1','foo 2','foo 3','foo 4','foo 5','foo 6','foo 7','foo 8','foo 9','foo 10','foo 11','foo 12');
$amount = 3;
shuffle($links);
$rand_list = array_slice($links, 0, $amount);
foreach ($rand_list AS $key => $link) {
print $link.'</br>';
}
?>
Considering 1 link per line:
$links = file("dati.txt");
$numLinks = count($links);
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
echo $randomLink;
Getting more links is simply a matter of a loop:
$links = file("dati.txt");
$numLinks = count($links);
$tmp = array();
for ($i = 0; $i < min(5, $numLinks); $i++)
{
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
// Avoid duplicates:
if (in_array($randomLink, $tmp))
{
$i--;
continue;
}
$tmp[] = $randomLink;
echo $randomLink;
}
$righe_msg = file("dati.txt");
$num = 5;
$selected = array();
while (count($selected)!=$num)
{
$rand = rand(0,count($righe_msg)-1);
$selected[$rand] = $righe_msg[$rand];
}
$numero=0;
foreach ($selected as $sel)
{
$dato = explode("|", trim($sel));
if (trim($dato[5])=="yes")
{
$numero++;
echo"<tr><td bgcolor='#EEEEEE'>» <a href='$dato[2]'> $dato[1]</a></td></tr> ";
}
}