Parse XML file within laravel - php

I want to select a XML file from my computer to be parsed. The form works and I can use the Input::file('file'); function. However I want to parse this document by favour with uploading it only as temporary file. When I want to parse it I get errors like: "unable to parse from string". It seems that parser can't find the file. I tried two parsers: SimpleXML and XMLParser(from orchestral).
public function uploadFile(Request $ file){
$data =Input::file('file');
$informationdata = array('file' => $data);
$rules = array(
'file' => 'required|mimes:xml|Max:10000000',
);
$validator= Validator::make($informationdata, $rules);
if($validator->fails()){
echo 'the file has not the correct extension';
} else{
XmlParser::load($data->getRealPath());
}
I also tried to parse it after storing the file.
private function store($data){
$destinationPath = public_path('uploads\\');
$fileName = $data->getClientOriginalName();
$data->move($destinationPath,$fileName);
$xml = simplexml_load_file($destinationPath.$fileName);
}
Thanks in advance for helping.

When you say "parse" what do you mean? Find nodes? Delete nodes? Add nodes? Or only read nodes?
Because you can find and read with the SimpleXMLElement class but if you want to add or delete I suggest you to use DomDocument instead.
Using SimpleXMLElement, the construct would be:
$xml = new SimpleXMLElement($destinationPath.$fileName, null, true);
While the DomDocument would be:
$xml = new DomDocument('1.0', 'utf-8'); // Or the right version and encoding of your xml file
$xml->load($destinationPath.$fileName);
After you create the object, you cand handle all the document.

It is unknown, whether you want to validate some exiting xml-file on your computer or want to implement the ability for users to upload any xml file and write some logic to cope this task. However, this is not the point.
I would recommend you to use the built-in to PHP core simplexml_load_file() function which has helped me with the project. Because you will never get Laravel to parse xml into some decent understendable array or object to work with through Request $file injections etc. This is good to work with html-forms or json, not with xml or other formats.
That's why you should work with object which will be the result of (for example) such code:
$xml_object = simplexml_load_file($request->file('action')->getRealPath());
And then you'll need to verify every xml node and field by yourself, writing some logic as you lose the possibility of using built-in to Laravel Illuminate\Http\Request validate() method.

Related

PARSING simple_html_dom results

I have the following code:
include('../scrape/simple_html_dom.php');
$file = "http://www.espn.com/golf/leaderboard?tournamentId=2233";
$html = new simple_html_dom();
$html->load_file($file);
foreach($html->find('table[class="leaderboard-table round-4"]') as $div){
$Rd1 = $div->find('td[class="round2 in post"]');
}
I'm attempting to parse the data from that url and then insert by 'class=full-name" the Round1, Round2, Round3 and Round4 scores.
Hower, I keep getting an error that this is an array to string conversion. Can anyone offer guidance? I can't even isolate the data to insert it into a DB.
It depends what your simple_html_dom() class does but just offhand, it's likely you have to first get the contents of the file and load that string since you don't have direct ownership of the file:
include('../scrape/simple_html_dom.php');
$file = "http://www.espn.com/golf/leaderboard?tournamentId=2233";
$html = new simple_html_dom();
# FETCH THE CONTENTS FIRST
$html = file_get_contents($file);
# THIS MAY BE LOADING A FILE, SO INSTEAD LOAD STRING
# PERHAPS THERE IS A load_string() METHOD?
$html->load_file($html);
/**Continue code...**/
If you need to load from a file, get the contents and temporarily store to a file using file_put_contents($html,'temp.txt'), then use the load_file() method...but it all depends what this class does.

trying to edit xml file using php simplexml

so I am trying to edit an xml file using php's simplexml extension but I am getting some problems and its
when I tried
$settings = simplexml_load_file("settings.xml");
....
if(isset($aInformation['cName']))
{
$settings->general->communityname = $aInformation['cName'];
$settings->asXML();
}
but I failed with the saving step...
$settings = simplexml_load_file("settings.xml");
$xmlconfigs = new SimpleXMLElement($settings);
....
if(isset($aInformation['cName']))
{
$settings->general->communityname = $aInformation['cName'];
$xmlconfigs->asXML();
}
but I failed too with the error
String couldn't be parsed to XML...
and I had tried searching on those posts before but they are the same as my failed example codes something edit XML with simpleXML and PHP SimpleXML error update xml file
Second one is not possible as SimpleXMLElement can only take a well-formed XML string or the path or URL to an XML document. But you are passing an object of class SimpleXMLElement returned by simplexml_load_file. That is the reason it was throwing error String couldn't be parsed to XML...
In first one the asXML() method accepts an optional filename as parameter that will save the current structure as XML to a file.
If the filename isn't specified, this function returns a string on
success and FALSE on error. If the parameter is specified, it
returns TRUE if the file was written successfully and FALSE
otherwise.
So once you have updated your XML with the hints, just save it back to file.
$settings = simplexml_load_file("settings.xml");
....
if(isset($aInformation['cName']))
{
$settings->general->communityname = $aInformation['cName'];
// Saving the whole modified XML to a new filename
$settings->asXml('updated_settings.xml');
// Save only the modified node
$settings->general->communityname->asXml('settings.xml');
}

Can I get an XML files structure without looking up the element names myself?

Using PHP, I would like to be able to open an XML file and get its structure without having to know any about the structure already. Is this possible?
I've been using XMLReader up until now but I'm parsing a wide variety of structures so it takes a while to go through each file manually and identify the structure.
I would only need to open the first parent node as every node after that would be the same.
e.g.
<name>
<first></first>
<second></second>
</name>
I would like to be able to identify this structure without having to manually look at the file first.
Happy to use other libraries than XMLReader but would need to stick with PHP.
Thanks!
DOMDocument should be able to do it.
$dom = new DOMDocument();
$dom->loadHTML($xml_data);
/* #var $names DOMNodeList */
$names = $dom->getElementsByTagName('name');
for($i=0;$i<$names->length;$i++){
$node = $names->item($i);
if($node->nodeName=='first'){
$first_name = $node->nodeValue; // store this
}elseif($node->nodeName=='second'){
$second_name = $node->nodeValue; // store this
}
}
Make sure that they are valid XML files.

How do I parse an external XML file (returned from a POST) with php?

I have a simple code written (based on some tutorials found around the internet) to parse and display an XML file. However, I only know how to reference an XML file stored on my server and I would like to be able to use an XML file that is being returned to me from a POST.
Right now my code looks like this:
if( ! $xml = simplexml_load_file('test.xml') )
{
echo 'unable to load XML file';
}
else
{
foreach( $xml as $event)
{
echo 'Title: ';
echo "$event->title<br />";
echo 'Description: '.$event->info.'<br />';
echo '<br />';
}
}
Is there some way I can replace the simpleXML_load_file function with one that will allow me to point to the POST URL that returns the XML file?
Use simplexml_load_string instead of loadfile:
simplexml_load_string($_POST['a']);
If you get the url to the file in the POST you can propably use the simplexml_load_file function with the url, but if that doesn't work you can use the file_get_contents in combination with the simplexml_load_string:
//say $_POST['a'] == 'http://example.com/test.xml';
simplexml_load_file($_POST['a']); // <-- propably works
simplexml_load_string(file_get_contents($_POST['a'])); //<-- defenitly works (propaly what happens internally)
also getting contents of external files could be prohibited by running PHP in safe mode.
If you are receiving a file that's been uploaded by the user, you can find it (the file) looking at the content of the $_FILES superglobal variable -- and you can read more about files uploads here (for instance, don't forget to call move_uploaded_file if you don't want the file to be deleted at the end of the request).
Then, you can work with this file the same way you already do with not-uploaded files.
If you are receiving an XML string, you can use simplexml_load_string on it.
And if you are only receiving the URL to a remote XML content, you have to :
download the file to your server
and, then, parse its content.
This can be done using simplexml_load_file, passing the URL as a parameter, if your server is properly configured (i.e. if allow_url_fopen is enabled).
Else, the download will have to be done using curl -- see curl_exec for a very basic example, and curl_setopt for the options you can use (you'll especially want to use CURLOPT_RETURNTRANSFER, to get the XML data as a string you can pass to simplexml_load_string).
From http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=php4:
If you do not want to save the
uploaded file directly but to process
it, the PHP functions
file_get_contents() and fread() can
help you. The file_get_contents()
function returns a string that
contains all data of the uploaded
file:
if (is_uploaded_file($_FILES['myFile']['tmp_name']))
$fileData = file_get_contents($_FILES['myFile']['tmp_name']);
That will give you a handle on the raw text within that file. From there you will need to parse through the XML. Hope that helps!
Check out simplexml_load_string. You can then use cURL to do the post and fetch the result. An example:
<?php
$xml = simplexml_load_string($string_fetched_with_curl);
?>

Using PHP to write to .swf files

I was wondering how to basically edit a .swf file using php, to change a single variable or to change more. How would I go about doing this? Is there a way to edit it without knowing machine code?
If there is an example of how to do this, where can I find it?
Thanks!
Or, if there is an easier way to go about doing this, please let me know!
take a look at libming
php documentation at http://docs.php.net/manual/en/book.ming.php
With Actionscript, it's very simple to load external data: XML and JSON are two standardized ways to do it, and both are easily generated by PHP. What exactly are you trying to do?
The question is old, but since it happens to coincide with what I've been working on, I figured I would put something together in case others find it useful. The solution works for AS3 only. It let you to change the values of instance variables and constants.
Suppose you have the following class:
package pl.krakow.rynek {
import flash.display.Sprite;
public class Advertisement extends Sprite {
private var title:String = 'Euro 2012 LIVE!';
/* ... */
}
}
You want the var title to be something else. The code for doing so is as follow:
<?php
require_once 'flaczki/classes.php';
// parse the SWF file, decoding only those tags needed by the injector
$input = fopen("input.swf", "rb");
$parser = new SWFParser;
$injector = new AS3ConstantInjector;
$swfFile = $parser->parse($input, $injector->getRequiredTags());
$classConstants = array(
'pl.krakow.rynek.Advertisement' => array(
'title' => 'Free Beer!'
)
);
// inject the values and reassemble the file
$injector->inject($swfFile, $classConstants);
$output = fopen($outPath, "wb");
$assembler = new SWFAssembler;
$assembler->assemble("output.swf", $swfFile);
?>
The code should be self-explanatory. The SWF file is first parsed, modifications are made, and the in-memory structure is saved to file. AS3ConstantInjector.inject() expects as the second argument an array of arrays keyed by the qualified names of the classes you wish to modify. The arrays themselves hold the new values for each class, with the key as the variable/constant name.
To see The variables in a SWF file, use AS3ConstantExtractor:
<?php
require_once 'flaczki/classes.php';
$input = fopen("button.swf", "rb");
$parser = new SWFParser;
$extractor = new AS3ConstantExtractor;
$swfFile = $parser->parse($input, $extractor->getRequiredTags());
$classConstants = $extractor->extract($swfFile);
print_r($classConstants);
?>
The Flaczki classes can be downloaded at http://code.google.com/p/flaczki/downloads/list
You can find out more about the Flaczki framework at the project development blog at http://flaczkojad.blogspot.com/
check out the SWF-library in php
Instead of thinking how to generate swf files, do the opposite and let the internal behavior depend on external logic in a php script. This way you never need to (re)compile your swf.

Categories