I have been trying to input untidy HTML and clean it by removing unwanted tags and attributes. I got only blank HTML as output with no lines in it .. Posting my code below .. Help me please.
index.php
<?php
//for converting tga to png or jpg
ini_set("memory_limit", "150M");
?>
<? ob_start(); ?>
<?php
/*
#name: Raja Gopal
#author: Raja Gopal
#discribe: Set Infotech Tool
#version: 1.2 Beta
*/
//file downloading after saving in "recodeit" folder
function download($file) {
if(file_exists($file)) {
if(ob_get_level()) {
ob_end_clean();
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
/*
MAIN
*/
if(count($_POST) && isset($_POST['submit'])) {
if(!empty($_POST['type'])) {
//upload file to the server
if(!empty($_FILES['files']['tmp_name'])) {
$dir = 'Original/';
$upload_dir = $dir . basename($_FILES['files']['name']);
$upload_dir = str_replace(" ", "", $upload_dir);
if(copy($_FILES['files']['tmp_name'], $upload_dir)) {
$flag = true;
} else {
$flag = false;
}
}
//get file format
$str[] = $_FILES['files']['name'];
$str = htmlspecialchars(implode('', $str));
$str_arr = explode('.', $str);
$result[] = $str_arr[count($str_arr)-1];
$result = implode('', $result);
$result = strtolower($result);
$result = str_replace(" ", "", $result);
//$result = trim($result);
//get file name with dots
$st[] = $_FILES['files']['name'];
$st = htmlspecialchars(implode('', $st));
$str_arr = explode('.', $st);
$i = 0;
$flname = '';
while($i < count($str_arr)-1) {
if($i == count($str_arr)-2) {
$flname .= $str_arr[$i];
} else {
$flname .= $str_arr[$i].'.';
}
$i++;
}
$flname = str_replace(" ", "", $flname);
//array with extensions
$arr = array();
$arr['html'] = array('html');
//format check
if($flag && array_key_exists($result, $arr)) {
$from = trim($result);
$to = $_POST['type'];
$format_res = $flname . '.' . $from;
$class = $from . $to;
//add classes from "classes" folder
if(require_once('classes/' . $class . '.php')) {
$fileclass = new $class($format_res, $flname);
//use our function to save the file
download('Recode/' . $flname . '.' . $to);
//delete Original folder
if(file_exists('Original/' . $format_res))
unlink('Original/' . $format_res);
//clear Recode folder
if(file_exists('Recode/'.$flname . '.' . $to))
unlink('Recode/'.$flname . '.' . $to);
exit();
}
}
}
}
?>
<? ob_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>HTML Cleaning Tool : Set Infotech Pvt Ltd</title>
<link href="style/style.css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--works faster becouse file is cached-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
//extensions select
$('.activated').live('click', function() {
$('.type_selected').removeClass('type_selected');
$('.input_type[value="' + $(this).val() + '"]').prop('checked',true);
$(this).addClass('type_selected');
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var filename;
var extensions = [];
var extension;
//array with our extensions
extensions['html'] = ['html'];
$('input[type="file"]').change(function(e) {
// Deselect the error message \ successful recoding
$('.type_selected').removeClass('type_selected');
$("#message").removeClass("visible").addClass("hidden");
//get file name and extention
var filepath = e.target.value.split('\\');
filename = filepath[filepath.length-1].split('.');
extension = filename[filename.length-1];
$('.file_type').not('.deactivated').removeClass('activated').addClass('deactivated');
//show possible extensions
if(extensions[extension.toLowerCase()] !== undefined) {
$.each(extensions[extension.toLowerCase()], function(k,v) {
$('.' + v).removeClass('deactivated').addClass('activated');
});
}
//show tick
$("#validation").css({
"background": "url('img/true.png') no-repeat"
});
//show cross
if(filename.length == 1) {
$("#validation").css({
"background-image": "url('img/false.png')"
});
}
});
//submit event
$('.submit').click(function() {
var text;
//message about the wrong extension
if(filename === undefined) {
$("#message").removeClass("hidden").addClass("visible");
$("#message").css({
"border": "2px solid #9c3232",
"background-color": "#d59e9e"
});
text = "<center>Your book is not loaded! Please select a book to start conversion!</center>";
$("#message").html(text);
$('.file_type').not('.deactivated').removeClass('activated').addClass('deactivated');
return false;
}
//message that there is no extension
if($('input[type="radio"]:checked').length==0) {
$("#message").removeClass("hidden").addClass("visible");
$("#message").css({
"border": "2px solid #9c3232",
"background-color": "#d59e9e"
});
text = "<center>You have to select the extension!</center>";
$("#message").html(text);
return false;
}
//message about successful conversion
if(filename !== undefined && $('input[type="radio"]:checked').length>0) {
$("#message").css({
"border": "2px solid #2e8856",
"background-color": "#5abd68"
})
$("#message").removeClass("hidden").addClass("visible");
text = "<center>Success ! Pleat Wait</center>";
$("#message").html(text);
$('.type_selected').removeClass('type_selected');
$.each(extensions[extension.toLowerCase()], function(k,v) {
$('.' + v).removeClass('activated').addClass('deactivated');
});
$("#validation").css({
"background-image": "url('img/false.png')"
});
setTimeout(function(){
$('input[type="file"]').val('');
}, 3000);
return true;
}
});
});
</script>
</head>
<body>
<div class="hole_wrap">
<!--WRAP CONTENT-->
<div id="content_wrap">
<!--BEGIN CONTENT-->
<div id="content">
<!--HEADER-->
<div id="header">
<div id="block" class="f_l">
<div id="head_text"><h1>HTML Cleaning Tool</h1></div>
<div id="text"><p>Set Infotech Pvt Ltd</p></div>
</div>
<div id="logo" class="f_r"></div>
<div class="clearfix"></div>
</div>
<!--END HEADER-->
<!--FORM BEGIN-->
<form class="form" name="f" method="POST" enctype="multipart/form-data" target="_blank">
<div id="loading_block" class="f_l">
<div id="head_text"><h1><center>1. Load Untidy HTML to Clean:</center></h1></div>
<!-- file load -->
<div class="upload_b f_l">
<input id="loading_f" class="files_load" type="file" name="files" size="10">
</div>
<div id="validation" class="f_r"></div>
<div class="clearfix"></div>
<div class="gr_line"></div>
<div id="head_text"><h1><center>2. Select HTML Below:</center></h1></div>
<!-- radios -->
<div class="formats f_l">
<center><input class="input_type" type="radio" name="type" value="html">
<!-- buttons -->
<button class="file_type html deactivated" type="button" value="html"></button></center>
</div>
<div class="clearfix"></div>
<!-- exec -->
<div class="gr_line"></div>
<div id="head_text"><h1><center>3. Clean HTML !</center></h1></div>
<input class="submit f_l" id="loader" type="submit" name="submit" value="Convert">
<div id="message" class="hidden f_l"><center></center></div>
</div>
<div class="clearfix"></div>
</form>
<!--END OF FORM-->
</div>
<!--END OF CONTENT-->
</div>
<!--END OF CONTENT WRAP-->
</div>
</body>
</html>
htmlhtml.php
<?php
class htmlhtml
{
/** #var string */
private $tag;
/** #var string */
private $attribute;
private $dom;
public function __construct($format_res, $flname)
{
// Turn up error reporting
error_reporting(E_ALL | E_STRICT);
// Upload template
$this->data = file_get_contents('Original/' . $format_res);
$this->dom = new DOMDocument();
$this->dom->strictErrorChecking = false;
$this->dom->formatOutput = true;
$this->dom->loadHTML(base64_decode($this->data));
$exceptions = array(
'a' => array('href'),
'img' => array('src')
);
$this->stripAttributes($exceptions);
$this->stripSpanTags();
$decoded = base64_decode($this->data);
$decoded = $this->stripNonBreakingSpaces($decoded);
file_put_contents('Recode/' . $flname . '.html', $decoded);
}
public function stripAttributes(array $exceptions)
{
$xpath = new DOMXPath($this->dom);
if (false === ($elements = $xpath->query("//*"))) die('Xpath error!');
/** #var $element DOMElement */
foreach ($elements as $element) {
for ($i = $element->attributes->length; --$i >= 0;) {
$this->tag = $element->nodeName;
$this->attribute = $element->attributes->item($i)->nodeName;
if ($this->checkAttrExceptions($exceptions)) continue;
$element->removeAttribute($this->attribute);
}
}
$this->data = base64_encode($this->dom->saveHTML());
}
public function checkAttrExceptions(array $exceptions)
{
foreach ($exceptions as $tag => $attributes) {
if (empty($attributes) || !is_array($attributes)) {
die('Attributes not set!');
}
foreach ($attributes as $attribute) {
if ($tag === $this->tag && $attribute === $this->attribute) {
return true;
}
}
}
return false;
}
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
protected function stripSpanTags ()
{
$nodes = $this->dom->getElementsByTagName('span');
while ($span = $nodes->item(0)) {
$replacement = $this->dom->createDocumentFragment();
while ($inner = $span->childNodes->item(0)) {
$replacement->appendChild($inner);
}
$span->parentNode->replaceChild($replacement, $span);
}
$this->data = base64_encode($this->dom->saveHTML());
}
/**
* Replace all entities within a string with a regular space
*
* #param string $string Input string
*
* #return string
*/
protected function stripNonBreakingSpaces ($string)
{
return str_replace(' ', ' ', $string);
}
}
Related
I am totally new to stackoverflow. I'm trying to adjust an excisting script in which an folder containing photo and video is getting loaded and displayed like a slideshow.
I'd like to add the option to load webpages also. Is there any easy way to do this?
Thank you so much.
This is my code:
<?php
include "class.getFiles.php";
$images = new getFiles();
// list of all files in the images folder (includes videos)
$imageArray = $images->getImageArray();
$sortedImages = new sortFiles();
$sortedImages->sortImageArray($imageArray);
// remove files not in the correct time period
$imageArray = $sortedImages->getImageArray();
$randImage = $sortedImages->randomImageNum();
$fileName = $imageArray[$randImage];
$info = new SplFileInfo($fileName);
?>
<!DOCTYPE html>
<html>
<head>
<title>Fiction Slideshow</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<?php
if($info->getExtension() == "mp4")
{
echo '<video id="vid" class="videoDisplay" autoplay>
<source src="images/'.$fileName.'" type="video/mp4">
Your browser does not support the video tag.
</video>';
echo '<script type="text/javascript">
var vid = document.getElementById("vid");
vid.addEventListener("ended", function(){
window.location.reload();
});
</script>';
}
else
{
echo '<img class="imageDisplay" src="images/'.$fileName.'" />';
echo '<script type="text/javascript">
setTimeout(function(){
window.location.reload();
}, 30000);
</script>';
}
?>
</body>
</html>
This is the class.getFiles.php file that the other script calls.
<?php
class getFiles{
protected $dir;
protected $imageArray;
function __construct()
{
$this->get_dir();
$this->get_images();
}
protected function get_dir()
{
$this->dir = getcwd();
}
protected function get_images()
{
if(count(scandir($this->dir."/images")) != 2)
{
$this->imageArray = scandir($this->dir."/images");
}
else
{
die("There are no files in the directory");
}
}
public function getImageArray()
{
return $this->imageArray;
}
}
class sortFiles{
protected $sortedImageArray = [];
public function sortImageArray($imageArray)
{
foreach ($imageArray as $imageFile )
{
if($imageFile !== ".." && $imageFile !== ".")
{
$imagePath = $imageFile;
$imageFile = (substr($imageFile, 0, -4));
$BeginningPos = strpos($imageFile, '_');
$beginningDate = (substr($imageFile, 0, $BeginningPos));
$beginningDateformatted = str_replace("-","/", $beginningDate);
$stringToStartTime = strtotime($beginningDateformatted);
$EndingPos = strpos($imageFile, '_', $BeginningPos + strlen('_'));
$EndingPos = $EndingPos + 1;
$EndingDate = (substr($imageFile, $EndingPos));
$EndingDateformatted = str_replace("-","/", $EndingDate);
$stringToEndTime = strtotime($EndingDateformatted);
$time = time();
if($time <= $stringToStartTime && $time >= $stringToEndTime)
{
array_push($this->sortedImageArray, $imagePath);
}
}
}
}
public function getImageArray()
{
if(count($this->sortedImageArray) != 0)
{
return $this->sortedImageArray;
}
else
{
die("There are no files in the time range");
}
}
public function randomImageNum()
{
$imageArrayLength = count($this->sortedImageArray);
$imageRand = rand(0, $imageArrayLength-1);
return $imageRand;
}
}
?>
Well you can save the web pages as links within your media folder. For example if you want to display the web page http://www.example.com, then you can create a file webpage1.txt inside the media folder. This file can have the link http://www.example.com.
In your code you can add a new condition that checks if the file type is txt. If the file type is txt, then your code can read the link inside the file and display the link using an iframe. The following code should work:
else if(strpos($fileName, "weblink") !== false)
{
/** The path to the web page link */
$file_path = (getcwd() . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . $fileName);
/** Read contents of file */
$web_page_link = file_get_contents($file_path);
/** Display the link in iframe */
echo "<iframe src='".$web_page_link."' width='100%' height='100%'></iframe>";
}
The above code should go above the else statement
Problem
I'm new to AJAX request so I believe I might be making a simple mistake, but whenever I want to run my script using an AJAX request I get a 500 (Internal Server Error)
Basically what I want to happen is if the user presses the #show-all button I will run a showall.php script that reads tasks from a data.txt file and prints the tasks in HTML on the webpage.
Any advice would be greatly appreciated!
PS: Line 24 refers to $.ajax({ and Line 27 refers to console.log("Error: " + error);
Code
Ajax request
$("#show-all").on("click", function () {
console.log("button pressed");
$.ajax({
url: '../p2/showall.php'
, error: function (error) {
console.log("Error: " + error);
}
, success: function (response) {
console.log("Success: " + response);
}
});
});
showall.php
<?php
$filename = 'data.txt';
include('file.php');
include('add.php');
$tasks = read_file($filename);
foreach($tasks as $task){
echo_task($task);
}
?>
file.php
<?php
//Write task element to file
function write_file($filename, $task){
$arr = array($task->title, $task->due_date, $task->priority, $task->course, $task->note);
$line = implode("\t", $arr);
$line .= "\n";
$file_pointer = fopen($filename, 'a' );
if ( ! $file_pointer ) { echo( 'error' ); exit; }
$error = fputs($file_pointer,$line);
fclose($file_pointer);
}
//Read file $filename and return array of Tasks
function read_file($filename){
$lines = file($filename);
if(!$lines){
print( 'error' );
exit;
}
$tasks = array();
foreach($lines as $line){
//Assume every entry should have notes
$arr = explode("\t", $line);
//Assume notes should not have \n in it
$arr[4] = str_replace("\n", "", $arr[4]);
$task = new Task($arr[0], $arr[1], $arr[2], $arr[3], $arr[4]);
$tasks[] = $task;
}
return $tasks;
}
?>
add.php
<?php
//Returns true if text field input isset & not empty string, otherwise returns false & echos issue to use
function validText($field){
if(isset($_POST['add'])){
if(isset($_POST[$field])){
if($_POST[$field] !== ''){
return true;
}
echo "<h3 class='error'>*Task $field cannot be empty</h3>";
return false;
}
echo "<h3 class='error'>*Task $field must be set</h3>";
return false;
}
return true;
}
//Return task from form elements
function task_from_form(){
if(isset($_POST['add']) && isset($_POST['title']) && isset($_POST['note'])){
if($_POST['title'] !== '' && $_POST['note'] !== ''){
$title = $_POST['title'];
$note = $_POST['note'];
$title_trim = trim($title);
$note_trim = trim($note);
$title_html = htmlentities($title_trim);
$note_html = htmlentities($note_trim);
$due_date = $_POST['due-date'];
$priority = $_POST['priority'];
$course = $_POST['course'];
$course_space = str_replace("-", " ", $course);
$task = new Task($title_html, $due_date, $priority, $course_space, $note_html);
return $task;
}
}
}
//Echo task
function echo_task($task){
echo "<div class='task row'>
<div class='task-title row'>
<button type='button' class='checkbox col'><span class='icon-checkbox-box' aria-hidden='true'></span></button>
<h1 class='col'>{$task->title}</h1>
<div class='task-info'>
<h2 class='due-date col task-date'>{$task->due_date}</h2>
<button type='button' class='priority {$task->priority} col'><span class='icon-circle' aria-hidden='true'></span></button>
</div>
</div>
<div class='task-details'>
<div class='row'>
<h2 class='col'>{$task->course}</h2> </div>
<div class='row'>
<p class='note col'>{$task->note}</p>
</div>
</div>
</div>";
}
?>
I believe this is not an ajax issue. If you visit http://localhost:8888/p2/showall.php I think you will get the same 500 error. Try to check your server, if its a php issue, create a html file to return same content as you want, will be easier to debug.
I have tried with fuction fopen, fwrite but I still can't make the it possible
I want to save my ajax guest book into txt file, please help me.
This is the index.php
<?php
error_reporting(E_ALL^E_NOTICE);
include "comment.class.php";
$comments = array();
foreach($comments as $c){
echo $c->markup();
}
?>
and it is the comment.class.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
/*
/ konstruktor
*/
$this->data = $row;
}
public function markup()
{
/*
/ method untuk comment
*/
//alias untuk &$this->data
$d = &$this->data;
$link_open = '';
$link_close = '';
if($d['url']){
$link_open = '<a href="'.$d['url'].'">';
$link_close = '</a>';
}
$d['dt'] = strtotime($d['dt']);
$url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
return '
<div class="comment">
<div class="avatar">
'.$link_open.'
'.$link_close.'
</div>
<div class="name">'.$link_open.$d['name'].$link_close.'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
I want to save the comment body into chat.txt
The following snippet will append the comments into the file instead of echoing them. See file_put_contents manual for details.
foreach($comments as $c){
file_put_contents( 'chat.txt', $c->markup(), FILE_APPEND );
}
I am collecting username, title, video count and comment count from html source. Consider this link
Here is my code to get it:
function getParameter($url)
{
$html = file_get_html($url);
if($html)
{
$containers1 = $html->find('div.v div.v-link v-meta-entry');
foreach($containers1 as $container)
{
$plays = $container->find('v-num'); // get nos of time video played
$item = new stdClass();
foreach($plays as $play)
{
$nos = $play->plaintext;
}
//echo $address;
}
$containers2 = $html->find('div.v div.v-link v-meta va a'); //get user name
foreach($containers2 as $username)
{
$user = $username->plaintext;
}
$containers3 = $html->find('div.v div.v-link a'); //get video title
foreach($containers3 as $title)
{
$title = $title->plaintext;
}
$commentcontainers = $html->find('div.ico-statcomment span'); //get nos of comments
foreach($commentcontainer as $cont)
{
$comments = $cont->plaintext;
}
return $data;
}
}
But it gives this error:
Warning: Invalid argument supplied for foreach() in /var/www/html/scrap/yelp/yoku.php on line 41
any hints for this?
Here is the source code snippet:
<div class="v" >
<div class="v-thumb">
<img src="http://r1.ykimg.com/0515000052B7B3D46714C0318106EA36" alt="和小姚晨约会激动抽筋" />
<div class="v-thumb-tagrb"><span class="v-time">08:56</span></div>
</div>
<div class="v-link">
</div>
<div class="v-meta va">
<div class="v-meta-neck">
<a class="v-useravatar" href="http://i.youku.com/u/UMTQxNDg3NzA4" target="_blank"><img title="嘻哈四重奏" src="http://g3.ykimg.com/0130391F455211D40E180C021BBB97D37C4057-26F4-2F53-A8CD-4A4139415701"></a>
<span class="v-status"> </span>
<a class="v-username" href="http://i.youku.com/u/UMTQxNDg3NzA4" target="_blank">嘻哈四重奏</a>
</div>
<div class="v-meta-title">和小姚晨约会激动抽筋</div>
<div class="v-meta-entry">
<i class="ico-statplay" title="播放"></i><span class="v-num">588万</span> <i title="评论" class="ico-statcomment"></i><span class="v-num">1,290</span> </div>
<div class="v-meta-overlay"></div>
</div>
</div>
Check selectors, documentation here simplehtmldom. For example, I did some changes in selectors.
function getParameter($url)
{
$html = file_get_html($url);
if($html)
{
//we iterate all 'div.v' and select data from every 'div.v' separately
$containersDiv = $html->find('div.v');
foreach($containersDiv as $div)
{
$containers1 = $div->find('div[class=v-meta va] div.v-meta-entry');
foreach($containers1 as $container)
{
$plays = $container->find('.v-num'); // get nos of time video played
$item = new stdClass();
foreach($plays as $play)
{
$nos = $play->plaintext;
}
//echo $address;
}
$containers2 = $div->find('div[class=v-meta va] a'); //get user name
foreach($containers2 as $username)
{
$user = $username->plaintext;
}
$containers3 = $div->find('div.v-link a'); //get video title
foreach($containers3 as $title)
{
$title = $title->plaintext;
}
$commentcontainers = $div->find('div[class=v-meta va] div.v-meta-entry span'); //get nos of comments changed
foreach($commentcontainer as $cont)
{
$comments = $cont->plaintext;
}
}
return $data;
}
}
Hello i want to call a function using jquery. I tried a lot of ways and I can't get it.
This my principal webpage.
I'am uploading a file csv and pressing 'Crear' button, it uplaod the file while call the function.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<SCRIPT type="text/javascript">
$(function (){
$('#btnxml').click(function (){
alert("aki");
$('#contenidos').load('csv.php');
});
});
</SCRIPT>
</head>
<body>
<form action="index.php" id="filecsv" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" id="file" name="up_csv[]"/>
<input type="submit" value="Cargar" name="btnxml" id="btnxml" /><br />
</form>
<?php
global $archivocsv;
//tipos de archivos permitidos
$extensionxml = array('csv','txt');
//destino
$rutaupcsv = './csv/';
//multicargador de archivos
$vt=0;
for($i=0;$i<count($_FILES['up_csv']['size']);$i++){
for ($j=-1; $j<count($extensionxml); $j++) {
if (strripos($_FILES['up_csv']['name'][$i], $extensionxml[$j])!== false) {
$filename = 'lista';
$destino = $rutaupcsv.$_FILES['up_csv']['name'][$i];
$archivocsv = basename($_FILES['up_csv']['name'][$i]);
move_uploaded_file($_FILES['up_csv']['tmp_name'][$i],$destino);
$vt=$vt+1;
break;
}
$ns=1;
}
}
?>
<div id="contenidos"></div>
csv.php
<?php
echo '<html>';
echo '<head>';
echo '<meta content="text/html;charset=utf-8" http-equiv="Content-Type">';
echo '<meta content="utf-8" http-equiv="encoding">';
echo '</head>';
function makecsv() {
global $archivocsv;
$csv = './csv/' . $archivocsv;
$doc = new DOMDocument();
$row = 1;
$handle = fopen($csv, "r");
# Rows Counter
$csvxrow = file($csv);
$csvxrow[0] = chop($csvxrow[0]);
$anzdata = count($csvxrow);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
#Load Predefined XML Template
$xml2 = $xml;
$xmlruta = './Templates/';
$xml = $xmlruta.$data[1].'.xml';
$doc->load($xml);
$xp = new DOMXPath($doc);
for ($c=0; $c < $num; $c++) {
foreach($xp->query('/ROOT/HEADER/#KEY[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#AUFNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#MATNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[1];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GAMNG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1AFFLL/E1FVOL/#MGVRG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GSTRS[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[3];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GLTRS[. != ""]') as $attrib)
{
$fecha = new DateTime($data[3]);
$fecha->add(new DateInterval('P1M'));
$attrib->nodeValue = $fecha->format('Y-m-d');
}
}
$name = $data[0] .'-'. $data[1];
$doc->formatOutput = true;
echo $doc->saveXML();
$rutafinal = './XML/';
$doc->save($rutafinal.$name.'.xml');
}
fclose($handle);
echo $anzdata . " XML Creados" . "<br />";
return $data;
}
makecsv();
echo '</html>';
?>
I can't call the function.
it doesn't do anything when i try to call it.
EDIT: I think the problem is in my function. function edite
Javascript can´t play with php directly because JS is client side (only in browser) and PHP is server side (only in browser). What you can do is a PHP file that has the code you want to invoke, and make JS call that page.
Separate the CVS code from the form and make JS call the new php with the CVS php functionality.
jQuery runs in the client's browser whereas your PHP is running on your web server. If you wish to call a PHP function from your jQuery code, your best option is to do so using AJAX.
You can find documentation for implementing an AJAX call in jQuery here: https://api.jquery.com/jQuery.ajax/
You'll need to print the actual hmtl to do the function.
PHP
<?php
print '<script> makecsv() </script>';
?>