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
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'])
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.
I'm having trouble with a foreach loop from a text file. I have a directory tree, and a list of these directories is in a text file, I want to check the tree against the list, and echo if any directories are missing.
The problem that I'm having is that I can't see an account for a new line, so if the file has 1 line, then it returns that it exists, but if the file has two line it returns the first as missing and the second as existing, even if it's the same entry twice in the file - see code below for clarification
<?php
$logFile = 'LogFile.txt';
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$verificationContents = file($verificationFile);
$fh = fopen($logFile,'a') or die("can't open file");
$new_line = "\r\n";
foreach($verificationContents as $directoryName) {
$subDirectory = $rootDirectory.$directoryName;
echo "$subDirectory <br />";
if (file_exists($subDirectory)) {
echo "$subDirectory Exists <br />";
} else {
echo "$subDirectory Does Not Exist <br />";
$libverificationfailed = 'failed';
fwrite($fh, "$subDirectory Not Found");
fwrite($fh, $new_line);
}
}
?>
So, as an example, the root directory has 2 sub directories, subdir1 and subdir2.
directoryverification.txt
subdir1
subdir2
and the page echos
C:\testdir\subdir1
C:\testdir\subdir1 Does Not Exist
C:\testdir\subdir2
C:\testdir\subdir2 Exists
So if there is a new line after the data in the text file, the code isn't reading it correctly. I'm hoping that this makes sense and that somebody can help.
regards,
Thanks rickdenhaan,
$subDirectory = rtrim($subDirectory);
Just before the if statement sorted it.
Try this
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$file = new \SplFileObject($verificationFile, 'r');
$file->setFlags(\SplFileObject::SKIP_EMPTY);
while ( $dirname = $file->fgets() )
{
$dirname = $rootDirectory . trim($dirname);
if ( !file_exists($dirname) )
{
echo sprintf("direcrory %s does not exist\n", $dirname);
continue;
}
echo sprintf("direcrory %s exists\n", $dirname);
}
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
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";
}
}