I am actually trying to build a website similar to this one :
https://robhammond.co/tools/seo-crawler
The concept is simple, you enter an URL of a website, and it follows every link you have inside it, in order to see if there is dead links.
I tried to do it recursively: looking at one page, find links, and look for each link I found, finds links on each page, etc.
I made an array of already visited links, so I won't check pages I've already checked.
Here is my code, I'm using a recursive ajax call to a PHP file that uses cURL, to get the error code, and find all the links inside it. After that, I make another ajax call for each link that is found.
Here is my code:
My html/javascript file :
<?php
session_start();
$_SESSION['visitedLinks'] = [];
?>
<html lang="fr">
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<title>Kaiman Crawler</title>
</header>
<body>
<form id="form" method="post" action="">
<label>
Veuillez saisir l'URL du site à scanner :
<input type="text" id='url' value="https://php.net/" required/>
</label>
<input type="submit" value="Scanner"/>
</form>
<p>Attention: Les pages avec plus de 200 liens ne seront pas traitées</p>
<table class="table" hidden>
<thead>
<tr>
<th scope="col"></th>
<th scope="col">URL</th>
<th scope="col">Titre de la page</th>
<th scope="col">Statut</th>
<th scope="col">Signification</th>
<th scope="col">Nombre de liens sur la page</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var cpt =1;
var request = 0;
var baseURL;
function signification(code){
switch (code) {
// TODO: Continuer les codes d'erreur
case 200:
return "Accessible";
case 404:
return "Page introuvable";
}
}
function scanPage(url) {
$.ajax({
url: 'getURLs.php',
dataType:'json',
type:'POST',
data:{
URL: url
}
}).done(function (data) {
console.log(data);
if (data['success']) {
$('tbody').append('<tr id="' + cpt + '"></tr>');
$('#' + cpt).append("<td>" + cpt++ + "</td>")
.append("<td>" + data['page'].url + "</td>")
.append("<td>" + data['page'].titre + "</td>")
.append("<td>" + data['page'].code + "</td>")
.append("<td>" + signification(data['page'].code) + "</td>")
.append("<td>" + data['page']['pages'].length + "</td>");
for (let i = 0; i < data['page']['pages'].length; ++i) {
if (data['page']['pages'].length >= 200){
break;
}
if (!data['links'].includes(data['page']['pages'][i]) && data['links'].includes(baseURL)) {
console.log(++request);
scanPage(data['page']['pages'][i]);
}
}
}
});
}
$('#form').submit(function (){
$('table').attr('hidden',false);
baseURL = $('#url').val();
$('thead').empty();
scanPage($('#url').val());
return false;
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</body>
</html>
My php file :
<?php
session_start();
require_once __DIR__ . '/Page.php';
$baseURL = $_POST['URL'];
$baseURL = explode('/',$baseURL,4);
$nomPage = $baseURL[3];
$baseURL = $baseURL[0] . "//". $baseURL[2] . '/';
$data = new stdClass();
$data->success = true;
$result = showLinks($baseURL,$nomPage);
if ($result === false){
$data->success = false;
}
else {
$data->page = $result;
$data->links = $_SESSION['visitedLinks'];
}
echo json_encode($data);
function showLinks($baseURL,$nomPage = "") {
if (!array_search($baseURL.$nomPage,$_SESSION['visitedLinks'])){
$result = fread_url($baseURL.$nomPage);
$var = $result[1];
$code = curl_getinfo($result[0], CURLINFO_HTTP_CODE);
$title = get_html_title($var);
array_push($_SESSION['visitedLinks'],$baseURL.$nomPage);
$page = new Page($baseURL . $nomPage, $title, $code);
preg_match_all("/a[\s]+[^>]*?href[\s]?=[\s\"\']+" .
"(.*?)[\"\']+.*?>" . "([^<]+|.*?)?<\/a>/",
$var, $matches);
$matches = $matches[1];
foreach ($matches as $var1) {
if (strlen($var1) >= 1) {
// si il ne s'agit pas d'une référence sur place ou à la racine
if ($var1[0] !== "#" && $var1 !== "/" && $var[0] !== "." && $var[0] !== "?" && $var[0] !== "%") {
// Si le dernier caractère n'est pas un /, l'ajouter
if ($var1[strlen($var1) - 1] !== "/") {
$var1[strlen($var1)] = "/";
}
// Si il s'agit d'un chemin absolu
if ($var1[0] === '/') {
$var1 = ltrim($var1, $var1[0]);
$page->addChild($baseURL . $var1);
} // Si il s'agit d'un chemin relatif
else if (strpos($var1, "http://") === false && strpos($var1, 'https://') === false && strpos($var1, 'www.') === false) {
$page->addChild($baseURL . $nomPage . $var1);
} // Sinon, si il s'agit d'une url
else {
$page->addChild($var1);
}
}
}
}
return $page;
}
else return false;
}
function fread_url($url,$ref="") {
$user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; ".
"Windows NT 5.0)";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_REFERER, $ref );
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
$html = curl_exec($ch);
return [$ch,$html];
}
function get_html_title($html){
preg_match("/\<title.*\>(.*)\<\/title\>/isU", $html, $matches);
return $matches[1];
}
And finally, my Page class
<?php
class Page implements JsonSerializable {
private $url;
private $titre;
private $code;
private $pages = array();
public function __construct($url,$titre,$code) {
$this->titre = $titre;
$this->url = $url;
$this->code = $code;
}
public function addChild ($child){
array_push($this->pages,$child);
}
/**
* Specify data which should be serialized to JSON
* #link https://php.net/manual/en/jsonserializable.jsonserialize.php
* #return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* #since 5.4.0
*/
public function jsonSerialize(){
return [
'url' => $this->url,
'titre' => $this->titre,
'code' => $this->code,
'pages' => $this->pages
];
}
}
Actually, this does work on Firefox, but it's using many resources. Plus, on Chrome, I get an ERR_INSUFFICIENT_RESOURCES on the console after some time on big websites.
So I'm asking you, is there a better way to optimize my code?
Thanks for your help.
Related
I hope they are well! I have a small problem, everything works perfect but it's not what I'm looking for, this function:
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
When updating JSON data, the data is updated at https://www.casadelpana.com/test but it reloads the entire page. I understand that it can be done with Ajax, I have not found something similar where I return the variables of my interest. How can I update data without reloading a page? Attached full code:
<?php
/*
Template Name: Test
*/
?>
<?php header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Formulario</title>
<title>Probando AP.I</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
</script>
</head>
<body>
<?php
$request = wp_remote_get( 'https://api.casadelpana.com/v1' );
if( is_wp_error( $request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $request );
/* mostrar json original
print_r($body); */
$data = json_decode($body);
/* mostrar json decode en PHP
echo '</br>';
print_r($data);
echo '</br>'; */
$vbs = $data->items['0']->valor; // tomar valor del bolivar respecto al dolar
$vars = $data->items['1']->valor; // tomar valor del peso ARS respecto al dolar
$tasaneta = $vbs / $vars;
$tasacomercial = $tasaneta * 0.85;
echo 'Valor del bolivar: '.$vbs.'';
echo '</br>';
echo 'Valor del Peso ARS: '.$vars.'';
echo '</br>';
echo 'Valor de tasa neta: '.round($tasaneta,0).'';
echo '</br>';
echo 'Valor de tasa comercial: '.round($tasacomercial,0).'';
// Hacer recorrido y obtener todos los valores.
/*
if( ! empty( $data ) ) {
echo '<ul>';
foreach( $data->items as $item ) {
echo '<li>';
echo '<b>' .$item->nombre. '</b>: ' . $item->valor . '</a>';
echo '</li>';
}
echo '</ul>';
}
*/
?>
</body>
</html>
Firstly your API is giving a JSON.
{
"items": [{
"id": "1",
"nombre": "Bolivar",
"valor": "3350"
}, {
"id": "2",
"nombre": "Pesos ARS",
"valor": "41"
}]
}
Without location.reload(); you can do like this.
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
// this will write first item of json to body tag
$("body").text(json.items[0].nombre + " : " + json.items[0].valor);
}
previous = current;
});
I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>
I have been struggling with this for a while now, I got some help from a similar question but I can't seem to make it work in my example.
I have an RSS feed on my website and what I am trying to do is display a message saying "No Warnings" when the RSS feed is blank/empty. If there is something in the RSS feed then I just want to show that.
For the life of me I can't get this to work! I can't get it to recognize the feed is blank...is this possible??
Here is my code,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Loading directly an RSS feed and displaying it</title></head>
<link type="text/css" href="rss-style.css" rel="stylesheet">
<body bgcolor="#FFE991">
<div id="zone" ><img src="/images/alert-icon-120.png" alt="Weather Warnings for SA. Issued by the Australian Bureau of Meteorology" align="left" style="padding-right: 4pt"width="15" height="15" border="0"/> Current South Australian Statewide Warnings:<small><em><font color="black"> Provided by The Bureau of Meteorology</font></em></small>
</div>
<fieldset class="rsslibbomsa">
<?php
require_once("rsslib.php");
$url = "http://www.bom.gov.au/fwo/IDZ00057.warnings_sa.xml";
$rss = RSS_Display($url, 15, false, false);
if ($rss == '')
{
// nothing shown, do whatever you want
echo 'No Current Warnings';
}
else
{
// something to display
echo $rss123;
}
?>
</fieldset>
</body>
</html>
If it helps RSS_Display is from the rsslib.php file, which I have provided below,
<?php
/*
RSS Extractor and Displayer
(c) 2007-2010 Scriptol.com - Licence Mozilla 1.1.
rsslib.php
Requirements:
- PHP 5.
- A RSS feed.
Using the library:
Insert this code into the page that displays the RSS feed:
<?php
require_once("rsslib.php");
echo RSS_Display("http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml", 15);
? >
*/
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("pubDate");
$tnl = $tnl->item(0);
$date = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$description = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["date"] = $date;
$y["description"] = $description;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title</li>\n";
}
$page .="</ul>/n";
return $page;
}
function RSS_Display($url, $size = 15, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
$description = $article["description"];
if($description != false)
{
$page .= "<br><span class='rssdesc'>$description</span>";
}
$page .= "</li>\n";
if($type==0)
{
$page .="</b><br />";
}
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
}
?>
Any help would be much appreciated.
Many thanks.
If you look at the rsslib code, you see that if the rss has no articles, the returned string will be \n.
The test to check if the RSS is empty should be if ($rss == "\n")
In addition to this, rsslib seems to be an old code (2010) and it is not object oriented (this is a problem because there are global vars defined outside the functions which can be in conflict with your code.
Moreover, this class does all the formatting of the RSS so if you want to change it, you will need to change the rsslib code.
You should consider using an other class like this one : https://github.com/dg/rss-php which is object oriented and easy to use.
I'm woking in a mobile friendly monitoring tool based on rrdtool.
All working fine but when I have the webpage opened for more that 1 hour freezes my computer.
I use this snippet for refresh the images.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
//echo "
//<script language='JavaScript'>
// function refreshIt(element) {
// setTimeout(function() {
// element.src = element.src.split('?')[0] + '?' + new Date().getTime();
// refreshIt(element);
// }, 50000);
// }
//</script>";
echo "
<script language='JavaScript'>
function refreshIt(element){
setInterval(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
}, 50000);
}
</script>";
?>
I include this php file in the pages what I have images and I want to refresh.
I tried the 2 options but as I said, freezes my browser.
Anyone have idea what can I do? Because I need refresh the images only, I don't want to refres the whole page.
EDIT
Here is the PHP script for print all images in database.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
if(isset($_GET['freq'])){
$freq = $_GET['freq'];
$title = 'Gráficas';
} else {
exit ("No has especificado la frecuencia");
}
if($freq == "hourly"){
$title = 'Tráfico última hora';
}
if($freq == "daily"){
$title = 'Tráfico último dia';
}
if($freq == "weekly"){
$title = 'Tráfico última semana';
}
if($freq == "monthly"){
$title = 'Tráfico último mes';
}
if($freq == "yearly"){
$title = 'Tráfico último año';
}
if(isset($_GET['limit'])){
$limit = $_GET['limit'];
} else {
$limit="10";
}
if(isset($_GET['inicio'])){
$inicio = $_GET['inicio'];
}
if(isset($_GET['subpage'])){
$subpage = $_GET['subpage'];
if ($subpage==1) {
$inicio=0;
}
} else {
$subpage = "1";
$inicio="0";
}
$total_records = $conn->query("SELECT graph_id FROM graph_".$freq)->num_rows;
$total_pages = ceil($total_records / $limit);
$sql = "SELECT graph_desc,graph_id,graph_name FROM graph_".$freq." ORDER BY graph_desc ASC LIMIT ".$limit." OFFSET ".$inicio.";";
$result = $conn->query($sql);
include_once 'adm/includes/pagination.php';
echo "<h1 id='titulo' class=\"page-header\">".$title."</h1>";
include_once 'adm/includes/refresh.php';
if ($total_pages != '1') {
echo "<div id='pager1' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<div class='graphSize' style='float:left; position:relative; z-index: 10;'>
<a href='?page=GraphDetail&graph_id=".$row['graph_id']."&graph_desc=".$row['graph_desc']."'>
<img style='width:100%' src='/graficas/".$freq."/".$row['graph_name']."' onload='refreshIt(this)'></img>
</a>
</div>
";
}
}
else {
echo "<p>No hay ninguna gráfica para mostrar</p>"; }
if ($total_pages != '1') {
echo "<div id='pager2' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
echo "</body>";
if(isset($_GET['fullscreen'])){
echo "<style>";
echo ".graphSize {";
echo "width:500px;";
echo "}";
echo "</style>";
}
$conn->close();
You have this onload handler for your image:
refreshIt(this)
...and that sets an interval (meaning it will repeat) every 50 seconds. The callback for that interval sets the src for the image, which means that onload will once again trigger, and you'll again do a set interval. So each time a new version of the image loads, you add another interval, so eventually you'll have tons of duplicating callbacks occurring.
You probably want to use setTimeout, or call refreshIt(this) once, not on every onload.
I want to select data from oracle and draw the chart but when I run the my code nothing else drawed.new3.php:
$tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SID = CLUSTDB1)))";
if ($conn = oci_connect("CAKTAS","******", $tns2)) {
echo "";
$stid = oci_parse($conn, "select wonum,STATUS, trunc( (sysdate-STATUSDATE) ) || 'd ' || trunc( mod((sysdate-STATUSDATE)*24,24) ) || ':' || trunc( mod( (sysdate-STATUSDATE)*24*60, 60 ) ) from maximo.WORKORDER_IT_VIEW where VFOPMGRGRP = 'IS_PRICHARHG' and STATUS <> 'COMPLETE' and STATUS <> 'CLOSE'");
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo json_encode($row);
} else {
die("could not connect to Maximo DB");
}
And it gives me correct array.
My html code:
<html>
<head>
<title>Kometschuh.de Tracker</title>
<!-- Load jQuery -->
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "new3.php", //my getting data php file
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Kometschuh.de Trackerdaten'
};
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
but in browser, I couldnt any chart
Refer my blog: http://howdyharish.wordpress.com/2014/08/11/create-google-charts-using-php-and-oracle-database/#more-3
Here is the code.
Index.php
<?php
ini_set(‘max_execution_time’, 123456);
$conn=oci_connect(‘username‘,’password‘,’DBname‘);
If (!conn)
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query= oci_parse($conn, “select col1, col2 from tablename“);
oci_execute($query);
$rows = array();
$table = array();
$table['cols'] = array(
array(‘label’ => ‘col1‘, ‘type’ => ‘string‘),
array(‘label’ => ‘col2‘, ‘type’ => ‘number‘),
);
$rows = array();
while($r = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
$temp = array();
//The below col names have to be in upper caps.
echo $r["COL1"];
$temp[] = array(‘v’ => (string) $r["COL1"]);
$temp[] = array(‘v’ => (int) $r["COL2"]);
$rows[] = array(‘c’ => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//Use the line below to see the data in jason format
//echo $jsonTable;
//Use the below lines of code to see data in a HTML table
/*echo “<table border=’1′ >\n”;
echo “<tr><th>col1</th><th>col2</th></tr>\n”;
while ($row = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo “<tr>\n “;
foreach ($query as $block) {
echo ” <td>” . ($block !== null ? htmlentities($block, ENT_QUOTES) : “ ”) . “</td>\n”;
}
echo “</tr>\n”;
}
echo “</table>\n”; */
?>
//In head section
<!–Load the Ajax API–>
<script type=”text/javascript” src=”https://www.google.com/jsapi”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>
<script type=”text/javascript”>
google.load(‘visualization’, ‘1’, {‘packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ‘name of the chart‘,
is3D: ‘true’,
width: 1000,
height: 600,
fontName: ‘Times-Roman‘,
fontSize: 23,
hAxis: {textStyle: {
fontName: ‘Times-Roman‘,
fontSize: ‘25‘ }}
};
//To create a line chart
var chart = new google.visualization.LineChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
//To create a column chart
var chart2 = new google.visualization.ColumnChart(document.getElementById(‘chart_div2′));
chart2.draw(data, options);
}
</script>
// In body section
<!–this is the div that will hold the pie chart–>
<div id=”chart_div” ></div>
<div id=”chart_div2″ ></div>
You cannot just use json_encode, the PHP output needs to be in the format that the Google API will understand (Google Documentation Here). So basically, you need to have some kind of function in php that transforms the OCI results into a JSON string readable by Google.
I have published a solution that works pretty well in my setup, other users might benefit from it. You can see my code on GitHub:
https://github.com/ernestomonroy/PHP-for-Google-Visualization-API
The php code looks as folows:
<?php
/*
* #author Ernesto Monroy <ehmizmg#gmail.com>
* #version 1.0
* This function takes the Connection Details and the SQL String and creates an two arrays, one for the column info
* and one for the row data. This is then passed to the arrayToGoogleDataTable that builds and outputs the JSON string
*
* Input for this is:
* $un: User Name
* $pw: Password
* $db: Connection String for the DB
* (e.g. '(DESCRIPTION=(CID=MyDB)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=MyDB)))' )
* (tip, if you are running your PHP and Oracle Instance on the same server 127.0.0.1 should be used)
*
* WARNINGS:
* -I have not included any Oracle Error Handling
* -I have not included any row limit, so if your query returns an unmanageable amount of rows, it may become an issue for you or your web users.
*FUTURE OPPORTUNITIES:
* -This functions only return type and label properties. If you want to use pattern, id or p (for styling) you can add a check when looping through the columns
* and try to detect a particular column name that you define as the property (EG. if oci_field_name($stid, $i)=="GOOGLE_P_DATA" then ....)
*/
function getSQLDataTable($un,$pw,$db,$SQLString){
$conn=oci_connect($un,$pw,$db);
$stid= oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
oci_execute($stid);
$stid= oci_parse($conn, $SQLString);
oci_execute($stid);
$ncols = oci_num_fields($stid);
$cols = array();
$rows = array();
$cell = array();
for ($i = 1; $i <= $ncols; $i++) {
$column_label = '"'.oci_field_name($stid, $i).'"';
$column_type = oci_field_type($stid, $i);
switch($column_type) {
case 'CHAR': case 'VARCHAR2':
$column_type='"string"';
break;
case 'DATE':
$column_type='"datetime"';
break;
case 'NUMBER':
$column_type='"number"';
break;
}
$cols[$i-1]=array('"type"'=>$column_type,'"label"'=>$column_label);
}
$j=0;
while (($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) != false) {
for ($i = 0; $i <= $ncols-1; $i++) {
switch(oci_field_type($stid, $i+1)) {
case 'CHAR': case 'VARCHAR2':
$cellValue='"'.$row[$i].'"';
$cellFormat='"'.$row[$i].'"';
break;
case 'DATE':
if($row[$i]==null){
$cellValue='""';
$cellFormat='""';
} else {
$cellValue=convertGoogleDate(date_create($row[$i]));
$cellFormat='"'.date_format(date_create($row[$i]), 'd/m/Y H:i:s').'"';
}
break;
case 'NUMBER':
$cellValue=number_format($row[$i], 2, '.', '');
$cellFormat='"'.$row[$i].'"';
break;
} //end of switch
$cell[$i]=array('"v"'=>$cellValue,'"f"'=>$cellFormat);
}
$rows[$j]=$cell;
$j++;
}
arrayToGoogleDataTable($cols, $rows);
}
/*This function takes in the columns and rows created in the previous function and returns the JSON String*/
function arrayToGoogleDataTable($cols, $rows) {
//Convert column array into google string literal
echo "{\n";
echo "\t".'"cols"'.": [\n";
for($i = 0; $i < count($cols)-1; $i++) {
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},\n";
}
//Last column without ending comma (},)
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}\n\t]";
//Now do the rows
//Check if empty first
if (count($rows)>0){
echo ",\n\t".'"rows"'.": [\n";
//For each row
for($j = 0; $j < count($rows)-1; $j++) {
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
//Last column without ending comma (},)
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]},\n";
}
//Last row
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]}\n";
echo "\t]";
}
echo"\n}";
}
/*This simply takes in a Date and converts it to a string that the google API recognizes as a Date*/
function convertGoogleDate(DateTime $inDate) {
$googleString='"Date(';
$googleString=$googleString.date_format($inDate, 'Y').',';
$googleString=$googleString.(date_format($inDate, 'm')-1).',';
$googleString=$googleString.(date_format($inDate, 'd')*1).',';
$googleString=$googleString.(date_format($inDate, 'H')*1).',';
$googleString=$googleString.(date_format($inDate, 'i')*1).',';
$googleString=$googleString.(date_format($inDate, 's')*1).')"';
return $googleString;
}
?>
For the rest of the implementation on Java and HTML check the git repo posted above
I know its a late reply, but still a top hit on Google and I have been asked the question a couple of times