Failed to show XML Data with PHP Script - php

I have about 60000 xml files that i have to insert into a MySQL database. so i thought about making a simple php script that would be executed for once to load data from this xml files and insert it into my db on a localhost.
Before inserting it into my DB i tried to show them on the data on the page but it shows nothing, and its type is NULL.
here is the code :
<?php
$dir = new DirectoryIterator('organismes');
foreach ($dir as $fileinfo) {
if (!$fileinfo -> isDot()) {
$XMLFILE = $fileinfo -> getFilename();
echo $XMLFILE . "<br>\n"; /*the filename shows correctly, so the DirectoryIterator is working*/
$pathtofile = "http://localhost/www/organismes/$XMLFILE"; /*the link to the xml file made with a variable*/
echo $pathtofile . "<br>\n"; /* the link shown is correct */
$xml = simplexml_load_file($pathtofile);
echo gettype($xml) . "<br>\n";
if ($xml == FALSE) {
echo "failed to load xml"; /* this message never shows so the xml file loads correctly */
} else {
$Org = $xml->Organisme->Nom; //this variable $Org gets a NULL Value
echo $Org . "<br>" ;
echo gettype($Org);
}
}
}
?>
when i used a print_r($xml), it shows some data so the file loads correctly.
and here is an example of the xml file that i have :
<Organisme id="adil-01053-01" codeInsee="01053" dateMiseAJour="2013-02-27" pivotLocal="adil">
<Nom>Agence</Nom>
<EditeurSource>A2 A3</EditeurSource>
<Adresse type="géopostale">
<Ligne>34, rue du Général-Delestraint</Ligne>
<CodePostal>01000</CodePostal>
<NomCommune>Bourg-en-Bresse</NomCommune>
<Localisation>
<Latitude>46.196535</Latitude>
<Longitude>5.2191997</Longitude>
<Précision>6</Précision>
</Localisation>
<Accessibilité type="ACC"/></Adresse>
<CoordonnéesNum>
<Téléphone>00000000000</Téléphone>
<Télécopie>00000000000</Télécopie>
<Email>adil.01#wanadoo.fr</Email>
<Url>http://www.adil01.org</Url>
</CoordonnéesNum>
<Ouverture><PlageJ début="vendredi" fin="vendredi"><PlageH début="09:00:00" fin="17:00:00"/></PlageJ><PlageJ début="lundi" fin="jeudi"><PlageH début="09:00:00" fin="18:00:00"/></PlageJ>
</Ouverture>
</Organisme>
so i am trying to figure it out why it doesn't show correctly and why it gets a NULL Value
So brothers if you can help that would be wonderful :)

$pathtofile = "http://www.w3schools.com/xml/note.xml";
$xml = simplexml_load_file($pathtofile);
if ($xml == FALSE) {
echo "failed to load xml";
}
else
{
$A = $xml->to;
echo "$A <br />";
}
Focusing on just that part of the code, it seems to work correctly. Either one of two things are happening. The "$xml->Organisme->Nom;" has a spelling error and/or the xml file being pulled does not include those field names.
For testing do
print_r($xml);
right after
echo "$A <br />";
to get an accurate representation of the xml file being pulled.
Hope this helps.

I am not exactly sure what you want but I assume you want to insert XML data into your database. If that's the case, try this:
function create_xml()
{
$xml = simplexml_load_file("file.xml");
$nodes = new SimpleXMLElement('file.xml', null, true)
or die("cannot create");
$i = 0;
foreach ($nodes->children() as $child)
{
$var= $child->xml_child;
$sql = "INSERT INTO ...)";
mysqli_query($connect, $sql);
$i++;
echo "xml set";
}
}

Related

How to integrate a link to parse in PHP Simple XML

I need to download all photos about estates from an XML to save on the server. Every estate child in the XMl has a general section with all information and then a node called Foto (estate's photos) and another one for plans (Planimetria). The link of every image is structured as is:
<Link>http://www.site.it/ImageView.ashx?id=[photoID]&reduce=1438[can be set as I want es: 1000, 960, 1080]</Link>
I need to call it inside the $url_photo and $url_plan so I can read the photoID from XML and set resolution (1438,1000,960) with a global variable.
This is my code:
<?php
$xml = simplexml_load_file("Schede.xml"); // your xml
$path = '/mnt/c/Users/Giuseppe/Desktop/FotoTest/';
$i = 1;
$resolution = '1000';
// Estate Image
foreach($xml->CR03_SCHEDE as $estate){
//if((string) $estate['ELIMINATO'] = "NO"){
echo "\nEstate n $i Images\n";
foreach($estate->Foto->CR04_SCHEDE_FOTO as $photo){
$url_photo = (string) $photo->Link;
$filename_photo = basename($photo->CR04_FILENAME); // get the filename
if(file_exists($path . $filename_photo)) {
echo "file $filename_photo already exists \n";
}
else {
$img_photo = file_get_contents($url_photo); // get the image from the url
file_put_contents($path . $filename_photo, $img_photo); // create a file and feed the image
echo "file $filename_photo created \n";
}
}
// Plans
echo "\nEstate n $i plans\n";
foreach($estate->Planimetria->CR04_SCHEDE_FOTO as $plan) {
$url_plan = (string) $plan->'http: // www.site.it/ImageView.ashx?id=' . $plan->ID . '&reduce=' . $resolution; //$plan->Link;
$filename_plan = basename($plan->CR04_FILENAME);
if(file_exists($path . $filename_plan)) {
echo "file planimetry $filename_plan already exists \n";
}
else {
$img_plan = file_get_contents($url_plan); // get the image from the url
file_put_contents($path . $filename_plan, $img_plan); // create a file and feed the image
echo "file planimetry $filename_plan created \n";
}
}
$i++;
/*}
else{
echo "$estate->attributes(Riferimento)"."Deleted\n";
}*/
}
?>
I also have a problem with the first if commented:
if((string) $estate['ELIMINATO'] = "NO")...
Eliminato is an attribute of CR03_SCHEDE but the script won't read it and in any case go inside the if.
The complete XML has about 70/80 properties and the foreach works well to download all images, but I need that it should download the only one that has that attribute equals to NO
This is the example of XML (only one estate): link
Thanks to all
This is a classic mistake:
if((string) $estate['ELIMINATO'] = "NO")
You used the assignment operator instead of the comparison operator. Please use this exact form:
if ('NO' == (string)$estate['ELIMINATO'])

How to get position of hyperlink tag while parsing DOCX document.xml with PHP?

My aim is to parse DOCX file with PHP for all hyperlinks in format:
<start of hyperlink(number of the first element of hyperlink in text)>,
<end of hyperlink(number of the last element of hyperlink in text)>,
<hyperlink text>
For example:
input: "Hello, absolutely terrible{adjective: distressing}(you cannot see this in .docx file) world!"
output: {19, 26, "adjective: distressing"}
For now I've done code to parse all the hyperlinks as plain text, but I cannot get numbers of its position in text. Here is my code:
define("dir", "Dictations");
define("test_file", "Dictation_Text.docx");
/**
* #param $filename
* #return string
*/
function getHyperLinks($filename) {
$explode_result = explode('.', $filename);
$extension = end($explode_result);
if ($extension == "docx") {
$dataFile = "word/document.xml";
}
else {
return "DOCX files only supported";
}
$zip = new ZipArchive;
if ($zip->open($filename) === true) {
if (($zip_index = $zip->locateName($dataFile)) !== false) {
$data = $zip->getFromIndex($zip_index);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $data, $values, $indexes);
xml_parser_free($parser);
$result = Array();
foreach ($indexes["W:HYPERLINK"] as $ind) {
if ($values[$ind]["type"] == "open") {
$result[] = $values[$ind]["attributes"]["W:ANCHOR"];
}
}
return $result;
}
else {
return "File " . $filename . " couldn't be found in " . document;
}
}
else {
return "Couldn't open archive " . $filename;
}
}
#TODO: getting filename from front by $_GET
$document = dir . "/" . test_file;
$result = getHyperLinks($document);
if (is_array($result)) {
foreach ($result as $res) {
echo $res . "\n";
}
}
else {
echo $result;
}
So I couldn't find any XML attribute of starting position of hyperlink, please tell me how to get it or some way to get it from XMLObject or maybe show me another more convenient way to parse DOCX file to get all the info I need.
Your approach looks generally fine, but you're looking in the wrong file.
.docx link elements aren't stored in document.xml. Weird, right?
word/_rels/document.xml.rels has all that data (or header1.xml.rels, etc.).
If you want to see the format, re-name your .docx to a .zip. Then you can extract it and view all the .xml files inside. Each link gets a line of XML, so if all you need are the links, you may not need to parse from document.xml at all.
If you do need context, you'll go by the association of the "Id" variable on each Relationship.

PHP Unlink doesn't delete the file on Windows machine

when I was using a Mac and MAMP the command worked fine but after moving the source code on Windows 10 and XAMPP now the following script doesn't delete the file but only move a copy of the file inside a folder (exported_files) and renaming the new file.
<?php
session_start();
error_reporting(0);
if (isset($_POST['ok']) && ($_POST['ok'] == 1))
{
//$arrayRicevuto = implode(" ",$arrayRicevuto);
if (!isset($_SESSION['countRows']) && empty($_SESSION['countRows']))
{
$_SESSION['countRows'] = $_POST['countRows'];
}
$data = date("dmY");
$filename = "EstrazioneParziale_del_" . $data;
$estensione = ".csv";
$fileOpen = fopen($filename.$estensione, "a") or die("Impossibile aprire il file");
foreach ($_POST['arrayFiltrato'] as $fields) {
fputcsv($fileOpen, $fields);
}
fclose($fileOpen);
$_SESSION['countRows']--;
if ($_SESSION['countRows'] == 0)
{
$finalData = date("h-i-s");
$directory="exported_files/";
copy($filename.$estensione, $directory.$_SESSION['email']."_".$filename.$finalData.$estensione);
unlink('$filename.$estensione');
unset($_SESSION['countRows']);
echo $directory.$_SESSION['email']."_".$filename.$finalData.$estensione;
}
} else {
echo "Errore! ";
}
?>
Can somebody give me a suggestion?
Many thanks in advance! :)
First problem: Don't use single quotes around variables as it will take the variable as a literal string instead of returning you its value. For example:
<?php
$test = "hello";
echo '$test'; // This will print $test
echo "$test"; // This will print hello
?>
In unlink();, you don't have to use quotes at all when using a variable.
Sometimes the system is unable to find the location of the file you're trying to delete with unlink(). In those cases, you can use realpath(); as it will return the absolute path towards the file you're trying to delete:
unlink(realpath($filename.$estensione));

PHP: Updating XML from PHP and Saving

I'm trying to update 1 particular node in an pre-existing xml file from php. The problem i'm having is that it doesn't seem to be saving to the xml file. Not sure why and any help here will be appreciated!
<?php
$itemNumber = $_GET["itemNumberField"];
$xmlFile = "items.xml";
if(file_exists($xmlFile))
{
// $doc = new DOMDocument('1.0');
// $doc->load($xmlFile);
$doc = DOMDocument::load($xmlFile);
$item = $doc->getElementsByTagName("item");
foreach($item as $node)
{
$itemNumberNode = $node->getElementsByTagName("itemNumber");
$itemNumberNode = $itemNumberNode->item(0)->nodeValue;
$qtyNode = $node->getElementsByTagName("quantity");
$qtyNode = $qtyNode->item(0)->nodeValue;
if ($itemNumberNode == $itemNumber)
{
$qtyNode++;
echo $qtyNode;
}
}
}
else
{
echo "file doesn't exist! <br/>";
}
$doc->save($xmlFile);
?>
Edit: Just to clarify, the adding to the node seems to be fine.
Solution: Turns out the reason it didn't save was because node of the adding. i had to either directly update it or assign an updated value to it.
$qtyNode = $node->getElementsByTagName("quantity");
$qtyNode = $qtyNode->item(0);
...
$qtyNode->nodeValue++;
I've just coded something similar, and found out that $doc->saveXML() just builds up the outgoing xml string. I added a file_put_contents for writing to the xml file and worked fine.
file_put_contents($xmlFile, $doc->saveXML());
You COPY the scalar value (string) into a variable. Then you change the variable.
$qtyNode = $qtyNode->item(0)->nodeValue;
if ($itemNumberNode == $itemNumber)
{
$qtyNode++;
echo $qtyNode;
}
$qtyNode is not a DOMNode object, but a string variable.
You will have to change the DOMNode::$nodeValue property directly or assign the variable to it.
$qtyNode = $qtyNode->item(0);
if ($itemNumberNode == $itemNumber)
{
$qtyNode->nodeValue++;
echo $qtyNode->nodeValue;
}
Chmod the folder in which you want to save xml file: set permissions to maxiamally 775.
If this not works try using Curl

Simplexml_load_file issue, variable gets NULL Value [duplicate]

I have about 60000 xml files that i have to insert into a MySQL database. so i thought about making a simple php script that would be executed for once to load data from this xml files and insert it into my db on a localhost.
Before inserting it into my DB i tried to show them on the data on the page but it shows nothing, and its type is NULL.
here is the code :
<?php
$dir = new DirectoryIterator('organismes');
foreach ($dir as $fileinfo) {
if (!$fileinfo -> isDot()) {
$XMLFILE = $fileinfo -> getFilename();
echo $XMLFILE . "<br>\n"; /*the filename shows correctly, so the DirectoryIterator is working*/
$pathtofile = "http://localhost/www/organismes/$XMLFILE"; /*the link to the xml file made with a variable*/
echo $pathtofile . "<br>\n"; /* the link shown is correct */
$xml = simplexml_load_file($pathtofile);
echo gettype($xml) . "<br>\n";
if ($xml == FALSE) {
echo "failed to load xml"; /* this message never shows so the xml file loads correctly */
} else {
$Org = $xml->Organisme->Nom; //this variable $Org gets a NULL Value
echo $Org . "<br>" ;
echo gettype($Org);
}
}
}
?>
when i used a print_r($xml), it shows some data so the file loads correctly.
and here is an example of the xml file that i have :
<Organisme id="adil-01053-01" codeInsee="01053" dateMiseAJour="2013-02-27" pivotLocal="adil">
<Nom>Agence</Nom>
<EditeurSource>A2 A3</EditeurSource>
<Adresse type="géopostale">
<Ligne>34, rue du Général-Delestraint</Ligne>
<CodePostal>01000</CodePostal>
<NomCommune>Bourg-en-Bresse</NomCommune>
<Localisation>
<Latitude>46.196535</Latitude>
<Longitude>5.2191997</Longitude>
<Précision>6</Précision>
</Localisation>
<Accessibilité type="ACC"/></Adresse>
<CoordonnéesNum>
<Téléphone>00000000000</Téléphone>
<Télécopie>00000000000</Télécopie>
<Email>adil.01#wanadoo.fr</Email>
<Url>http://www.adil01.org</Url>
</CoordonnéesNum>
<Ouverture><PlageJ début="vendredi" fin="vendredi"><PlageH début="09:00:00" fin="17:00:00"/></PlageJ><PlageJ début="lundi" fin="jeudi"><PlageH début="09:00:00" fin="18:00:00"/></PlageJ>
</Ouverture>
</Organisme>
so i am trying to figure it out why it doesn't show correctly and why it gets a NULL Value
So brothers if you can help that would be wonderful :)
$pathtofile = "http://www.w3schools.com/xml/note.xml";
$xml = simplexml_load_file($pathtofile);
if ($xml == FALSE) {
echo "failed to load xml";
}
else
{
$A = $xml->to;
echo "$A <br />";
}
Focusing on just that part of the code, it seems to work correctly. Either one of two things are happening. The "$xml->Organisme->Nom;" has a spelling error and/or the xml file being pulled does not include those field names.
For testing do
print_r($xml);
right after
echo "$A <br />";
to get an accurate representation of the xml file being pulled.
Hope this helps.
I am not exactly sure what you want but I assume you want to insert XML data into your database. If that's the case, try this:
function create_xml()
{
$xml = simplexml_load_file("file.xml");
$nodes = new SimpleXMLElement('file.xml', null, true)
or die("cannot create");
$i = 0;
foreach ($nodes->children() as $child)
{
$var= $child->xml_child;
$sql = "INSERT INTO ...)";
mysqli_query($connect, $sql);
$i++;
echo "xml set";
}
}

Categories