search
HomeBackend DevelopmentPHP TutorialCool HTML5 interactive chart based on PHP_PHP tutorial

Cool HTML5 interactive chart based on PHP

Implement professional-grade web-based charts in PHP without in-depth knowledge of HTML5 and JavaScript.

Introduction

Recently, I needed to quickly create a chart from a set of PHP data sets. Charts must be interactive, user-friendly, and downloadable. After evaluating a number of PHP charting solutions, including phpChart, pChart, and Highcharts, I decided on phpChart as my tool of choice.

Background

As a main backend programmer, I neither have a lot of time to slowly study the use of JavaScript (customers want to see charts online within 24 hours), nor do I have the advanced skills Front-end coding knowledge. Basically, I want PHP developers with barely any front-end programming experience to be able to quickly develop beautiful charts.

I tried pChart, a popular PHP charting library. The generated charts look pretty good, although they are downloadable, but the charts are all static images. Highcharts seems to be the best choice. The chart looks stunning, is animated, and has many customization options, but at the same time, it is also very complex and requires a lot of JavaScript knowledge. Highcharts is neither designed for PHP nor is it free for business use.

Basic elements of phpChart

What I like most about phpChart is that it allows people to start with simplicity and minimal code.

The lite version of phpChart can be downloaded from http://phpchart.org/downloads/. Download the file and extract it to the website root directory.

Set conf.php

The first thing we need to do is set the variable SCRIPTPATH to the PhpChart class library in the conf.php file. This variable represents the relative or absolute URL of the phpChart library on your web server.

<ol class="dp-j"><li class="alt"><span><span>define(</span><span class="string">'SCRIPTPATH'</span><span>,</span><span class="string">'/phpChart/'</span><span>); </span></span></li></ol>

Create the simplest chart

<ol class="dp-j"><li class="alt"><span><span>包含PHP头文件conf.php: </span></span></li><li><span>require_once(<span class="string">"../conf.php"</span><span>); </span></span></li></ol>

Call the constructor C_PhpChartX and finally call the draw() function.

<ol class="dp-j"><li class="alt"><span><span>$pc=</span><span class="keyword">new</span><span> C_PhpChartX(array(array(</span><span class="number">123</span><span>, </span><span class="number">34</span><span>, </span><span class="number">51</span><span>, </span><span class="number">22</span><span>, </span><span class="number">3</span><span>)), &lsquo;simplest_graph&rsquo;); </span></span></li><li><span>$pc->draw(); </span></li></ol>

This is the code you need to get started. Below is the rendered output.

This is what I call minimal coding. There's no point in learning the basics the hard way when you have a team of programmers working on it. One thing any programmer wants to do as soon as possible is immerse themselves in complex documentation from a new set of libraries or tools.

By the way, the name of the second parameter in the constructor should be unique to your chart. I typed "simplest_graph", but it could be any non-space string. It must be a unique value so you can have multiple charts on one page.

Add title

You should add a title to your chart so users know what they are looking at.

<ol class="dp-j"><li class="alt"><span><span>$pc->set_title(array(</span><span class="string">'text'</span><span>=>&rsquo;My Simplest Graph')); </span></span></li></ol>

Add animation

One of the things pChart can't do is animation. In phpChart, animation support is available by simply calling set_animate and passing a true value.

<ol class="dp-j"><li class="alt"><span><span>$pc->set_animate(</span><span class="keyword">true</span><span>); </span></span></li></ol>

That’s it. At this point your chart should have a title and animation. The complete code is as follows:

<ol class="dp-j"><li class="alt"><span><span>$pc = </span><span class="keyword">new</span><span> C_PhpChartX(array(array(</span><span class="number">123</span><span>, </span><span class="number">34</span><span>, </span><span class="number">51</span><span>, </span><span class="number">22</span><span>, </span><span class="number">3</span><span>)),</span><span class="string">'simplest_graph'</span><span>); </span></span></li><li><span>$pc->set_animate(<span class="keyword">true</span><span>); </span></span></li><li class="alt"><span>$pc->set_title(array(<span class="string">'text'</span><span>=></span><span class="string">'My Simplest Graph'</span><span>)); </span></span></li><li><span>$pc->draw(); </span></li></ol>

Code content

If you view the source in the browser, you will find that phpChart automatically includes many JavaScript and CSS files, including jquery.js, jquery-ui, and jqplot.js, jquery-ui.css, etc. Although the charts are rendered in the browser via client-side JavaScript, the code on the front end is entirely PHP.

The reason why it’s popular is that as a PHP developer, I no longer have to worry about JavaScript because phpChart will take care of it for me. Below is the entire JavaScript code generated when viewing the source code - the result of my previous four lines of PHP code.

<ol class="dp-j"><li class="alt"><span><span><script language=</span><span class="string">"JavaScript"</span><span> type=</span><span class="string">"text/javascript"</span><span>> </span></span></li><li><span>     var _simplest_graph_plot_properties; </span></li><li class="alt"><span>    $(document).ready(function(){ </span></li><li><span>    setTimeout( function() { </span></li><li class="alt"><span>    _simplest_graph_plot_properties = { </span></li><li><span>    <span class="string">"title"</span><span>:{ </span></span></li><li class="alt"><span>    <span class="string">"text"</span><span>:</span><span class="string">"My Simplest Graph"</span><span>,</span><span class="string">"show"</span><span>:</span><span class="number">1</span><span> </span></span></li><li><span>    },<span class="string">"animate"</span><span>:</span><span class="keyword">true</span><span>,</span><span class="string">"animateReplot"</span><span>:</span><span class="keyword">true</span><span> </span></span></li><li class="alt"><span>    } </span></li><li><span> </span></li><li class="alt"><span>    $.jqplot.config.enablePlugins = <span class="keyword">true</span><span>; </span></span></li><li><span>    $.jqplot.config.defaultHeight = <span class="number">300</span><span>; </span></span></li><li class="alt"><span>    $.jqplot.config.defaultWidth = <span class="number">400</span><span>; </span></span></li><li><span>    _simplest_graph= $.jqplot(<span class="string">"simplest_graph"</span><span>, </span></span></li><li class="alt"><span>           [[<span class="number">123</span><span>, </span><span class="number">34</span><span>, </span><span class="number">51</span><span>, </span><span class="number">22</span><span>, </span><span class="number">3</span><span>]], _simplest_graph_plot_properties); </span></span></li><li><span> </span></li><li class="alt"><span>    }, <span class="number">200</span><span> ); </span></span></li><li><span>    }); </span></li><li class="alt"><span></script> </span></li></ol>

As you may also notice, "simplest_graph<span style="color: #111111; font-family: 'Segoe UI', Arial, sans-serif;">"<code><span style="color: #111111; font-family: 'Segoe UI', Arial, sans-serif;">”</span> is used as part of a JavaScript variable, such as _simplest_graph_plot_properties representing a jqplot object. This is why I said earlier that naming must be unique.

Additionally, the PHP data array is automatically converted to a JavaScript array, so the following PHP array:

<ol class="dp-j"><li class="alt"><span><span>array(array(</span><span class="number">123</span><span>, </span><span class="number">34</span><span>, </span><span class="number">51</span><span>, </span><span class="number">22</span><span>, </span><span class="number">3</span><span>)) </span></span></li></ol>

becomes a JavaScript array:

<ol class="dp-j"><li class="alt"><span><span>[[</span><span class="number">123</span><span>,</span><span class="number">34</span><span>,</span><span class="number">51</span><span>,</span><span class="number">22</span><span>,</span><span class="number">3</span><span>]] </span></span></li></ol>

Change renderer type

PhpChart supports bar chart, line chart and stack chart; strip chart; block chart; bubble chart; candle chart; gecko chart; meter chart ; and several other types of charts. Renderer support:

  • BarRenderer

  • BezierCurveRenderer

  • BlockRenderer

  • BubbleRenderer

  • CanvasAxisLabelRenderer

  • CanvasAxisTickRenderer

  • CategoryAxisRenderer

  • DateAxisRenderer

  • DonutRenderer

  • EnhancedLegendRenderer

  • FunnelRenderer

  • LogAxisRenderer

  • MekkoAxisRenderer

  • MekkoRenderer

  • MeterGaugeRenderer

  • OHLCRenderer

  • PyramidAxisRenderer

  • PieRenderer

如果你不指定类型的话,默认图表类型是折线图。要更改图表类型,需要调用set_series_default函数。例如,将上面的例子更改为饼图

<ol class="dp-j"><li class="alt"><span><span>$pc->set_series_default(array(</span><span class="string">'renderer'</span><span>=></span><span class="string">'plugin::PieRenderer'</span><span>)); </span></span></li></ol>

请注意,我用的是phpChart企业版。 phpChart精简版只支持折线图。

数组和命名约定

这里还有一些值得注意的地方。首先,phpChart函数中使用的几乎所有参数是一个数组,不是全部,但几乎所有的都是。只需记住这一点,就能避免 调试时的大量头痛问题后面我将简要地覆盖调试功能)。其次,渲染器在phpChart中被称为“插件”,故而你必须像这样传递 “plugin::PieRenderer”,中间双冒号。对于自定义JavaScript中,用 “js::yourJavascriptFunctioName”。

高级phpChart:自定义JavaScript

到目前为止,所有我展示的都是PHP。在大多数情况下,对于简单的PHP函数调用,phpChart完全能做得很好。为了充分利用 phpChart,你或许会想要使用自定义JavaScript。例如,你可以用phpChart从JavaScript函数和外部源加载数据。

下面的sineRenderer是一个自定义JavaScript函数,用于定义从一组随机数显示正弦值。然后传递给set_data_renderer函数。

PHP:

<ol class="dp-j"><li class="alt"><span><span>$data1 = array(); </span></span></li><li><span>$pc = <span class="keyword">new</span><span> C_PhpChartX(array($data1),</span><span class="string">'basic_chart_4'</span><span>); </span></span></li><li class="alt"><span>$pc->set_title(array(<span class="string">'text'</span><span>=></span><span class="string">'Basic Chart with Custom JS'</span><span>)); </span></span></li><li><span>$pc->set_data_renderer(<span class="string">"js::sineRenderer"</span><span>); </span></span></li><li class="alt"><span>$pc->add_plugins(array(<span class="string">'pointLabels'</span><span>)); </span></span></li><li><span>$pc->set_animate(<span class="keyword">true</span><span>); </span></span></li><li class="alt"><span>$pc->draw(); </span></li><li><span> </span></li><li class="alt"><span>JavaScript: </span></li><li><span> </span></li><li class="alt"><span>sineRenderer = function() { </span></li><li><span>    var data = [[]]; </span></li><li class="alt"><span>    <span class="keyword">for</span><span> (var i=</span><span class="number">0</span><span>; i<</span><span class="number">13</span><span>; i+=</span><span class="number">0.5</span><span>) { </span></span></li><li><span>      data[<span class="number">0</span><span>].push([i, Math.sin(i)]); </span></span></li><li class="alt"><span>    } </span></li><li><span>    <span class="keyword">return</span><span> data; </span></span></li><li class="alt"><span>  }; </span></li></ol>

想要知道set_data_renderer函数的更多内容可点击这里:http://phpchart.org/phpChart/docs/output/C_PhpChartX_set_data_renderer@.html

导出图表到图片

刚开始的时候,对此我很困扰,因为我不知道如何导出图表。事实证明,phpChart图表可以导出为可下载的图片,但这个过程并没有很好的记录下来。我发现添加以下代码到所有页面的底部,就可以扭转乾坤:

<ol class="dp-j"><li class="alt"><span><span><script type=</span><span class="string">"text/javascript"</span><span> </span></span></li><li><span>  src=<span class="string">"http://www.codeproject.com/phpChart/js/showjs.js"</span><span>></script> </span></span></li></ol>

下载showjs.js:http://phpchart.org/phpChart/js/showjs.js

调试phpChart

最后,在结束之前,我要提一提phpChart的一个非常宝贵的特点。那就是它的内置调试功能。在其网站上,所有的在线例子http://phpchart.org/examples/)都有调试可以启用生动的演示和两个清晰的可方便移植下面代码的选项卡——分别是JavaScript和PHP。

要启用调试,只需添加以下代码行到conf.php文件:

<ol class="dp-j"><li class="alt"><span><span>define(</span><span class="string">'DEBUG'</span><span>, </span><span class="keyword">true</span><span>); </span></span></li></ol>

最后的思考

PhpChart的一个主要好处是,通过使用这个工具,PHP程序员可以实现专业级的基于Web的图表——而无需深入了解HTML5和JavaScript知识。

如果你像我一样,也是前端编程的门外汉,但同样需要生成交互式的Web图表,那么你或许会喜欢phpChart。关于phpChart的HTML5图表例子已经完整地罗列到以下这个页面中。运气好的话,你也许并不需要文档——就可以直接理解代码。



www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1031255.htmlTechArticle基于PHP的超炫酷HTML5交互式图表 用PHP实现专业级的基于Web的图表,而无需深入的HTML5和JavaScript知识。 介绍 最近,我需要从一组PHP数据组快...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool