How to integrate a link to parse in PHP Simple XML - php

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'])

Related

Cannot upload image using filepath in MS-Azure Blob Storage

I am developing a web application using Microsoft Azure services. I am following this link to upload an image to my blob storage, but there are a few bits and pieces missing in the document that leads to certain issues. For instance, how do we define the variable $fileToUpload and how will it relate to the variable $myfile? Also, if we want to choose to upload a file from our system when the application is running, in which of the two variables should we have the absolute file path to my image? The code I have written till now to upload an image is as follows:
function imageupload(string $current_user){
$pt_id = $_POST['patientid'];
if (strcmp($pt_id,"")==0){
echo "Select PatientID to continue";
}else{
$accountexists = load($current_user, $pt_id);
if ($accountexists == 0){
$error = "Patient Id does not exist";
echo $error;
}else{
$img_path = $_POST['uploadI'];
if (strcmp($img_path, "")==0){
echo "Enter valid image path <br />";
}
else{
require_once 'vendor/autoload.php';
$connectionString = '****';
// Create blob client.
$blobClient = BlobRestProxy::createBlobService($connectionString);
# Create the BlobService that represents the Blob service for the storage account
$containerName = $current_user;
$num = rand(10,10000);
$num2 = (string) $num;
$fileToUpload = $pt_id."_".$num2;
# Upload file as a block blob
echo "Uploading image: ".PHP_EOL;
echo $img_path;
echo "<br />";
$content = fopen($img_path, "r");
//Upload blob
$blobClient->createBlockBlob($containerName, $fileToUpload, $content);
echo "Image uploaded successfully! <br />";
}
}
}
}
In this code, I am storing my path to the image in the variable $img_path. And this is the code I am using for displaying the image later:
// Gets all the images from the hospital's container and filters out the images corresponding to a particular patient.
// For the patient, the image would be saved on cloud with name as: <patientid>_<some random number>
// Eg- patient id= pt1 , so image name could be- pt1_3682
function uploadedimage(string $current_user, string $HospitalId, string $PatientId){
$containerName = $HospitalId;
$url = "";
try{
// Get blob.
require_once 'vendor/autoload.php';
// use MicrosoftAzure\Storage\Common\ServicesBuilder;
$connectionString = '****';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$blob_list = $blobClient->listBlobs($containerName);
$blobs = $blob_list->getBlobs();
$strlen = strlen($PatientId);
$array_user = array();
// echo "These are the blobs present in the container: ";
foreach($blobs as $blob)
{
$name = $blob->getName();
$namesub = substr($name,0, $strlen);
if (strcmp($namesub, $PatientId) == 0){
array_push($array_user, $blob);
}
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
$url = "";
try {
foreach($array_user as $blob)
{
$name = $blob->getName();
$url = $blob->getUrl();
echo "<img src=\"".$url."\" alt=\"image post\"></br></br>";
}
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
But I cannot seem to view my image in the html that I have specified. All I get is the default text "image post". Thus I have concluded there is something I am missing in my code due to which the images are not being uploaded but I can't seem to figure that out from the azure tutorial.
Edit: I checked my blob properties and they are all of 0 size, which means that they are not being uploaded properly. Also I realised that there are some images that were pushed to the cloud along with my code in my git folder. So if there is a particular image by the name abc.png already existing in the same directory as my code on Azure and while uploading this image from my web application, if in the path text box I specify only abc.png, that image gets uploaded in my container in it's correct size, but if that same image is present on my desktop and if I specify the complete filepath of my local system for this image (or some other image not present in the git directory existing on azure) as C:/Desktop/abc.png, it gets uploaded as only 0 bytes image (which is essentially not being uploaded properly). What can be the issues if it is not able to take images from my system and can only take the images already existing in it's git directory?

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.

Why is file_exists() returning false?

I'm trying to retrieve images for WP posts, which are held in a wp-uploads directory, using if (file_exists() but it's not recognising the file path.
For each post, there are up to 8 images available. Each image has the letters a-g at the end of the file name (or nothing), and has str_replace to replace certain characters in the file names.
I need to show each image if it exists, and if not, to return nothing. So if the post is associated with images with b, d and f at the end, it just shows those three.
I've tested without the (file_exists()) and its able to pick up the images with a simple echo for each - but it seems the $img paths aren't being recognised.
Im a bit of a php noob so any help would be appreciated...
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
$imga = $root.$path."a.jpg";
$imgb = $root.$path."b.jpg";
$imgc = $root.$path."c.jpg";
$imgd = $root.$path."d.jpg";
$imge = $root.$path."e.jpg";
$imgf = $root.$path."f.jpg";
$imgg = $root.$path."g.jpg";
if (file_exists($img)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imga)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imgb)) { echo "<img src='".$root.$path."b.jpg' />"; } else { echo ""; }
if (file_exists($imgc)) { echo "<img src='".$root.$path."c.jpg' />"; } else { echo ""; }
if (file_exists($imgd)) { echo "<img src='".$root.$path."d.jpg' />"; } else { echo ""; }
if (file_exists($imge)) { echo "<img src='".$root.$path."e.jpg' />"; } else { echo ""; }
if (file_exists($imgf)) { echo "<img src='".$root.$path."f.jpg' />"; } else { echo ""; }
if (file_exists($imgg)) { echo "<img src='".$root.$path."g.jpg' />"; } else { echo ""; }`
You need to rearrange the way you are telling PHP to look up the address,
$root is probably not your absolute file path root (probably meaning absolutely) so instead use the special super variable for this, $_SERVER['DOCUMENT_ROOT'] which is the root of the web accessible filepath, therefore you then have:
$img = $_SERVER['DOCUMENT_ROOT'].$root.path.".jpg"
//while retaining your current / at the start of $root
This is the file structure to check if the file exists, not the file structure to reference in the <img> tag, that appears to be correct in your examples above.
So, your overall correction should look like this:
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
...
if (file_exists($_SERVER['DOCUMENT_ROOT'].$img)){
....
}
An additional note is that the results of this function are cached so you should call clearstatcache() at the start of this file so that it can make fresh checks for if the images exist. Currently without this even if the image does exist, PHP will be using the cached - past- results which may not be up to date.
You start $root with a /, therefore it's starting from the server's root directory. Remove the first / and retry.
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$uploads = wp_upload_dir();
Get base root directory.
$root = $uploads['path'];
$imgDir = $root.$path.".jpg";
if (file_exists($imgDir)){
.......
}

Failed to show XML Data with PHP Script

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";
}
}

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