I want to save xml document in mysql database as below:
$_docId= $this->getRequest()->getParam('docId', 0);
$_slmData = '<SLM_form_v2 id="slmform"><group_1_1><section1_1/><name1_1>sdfds</name1_1>
enter code here<localname1_2/><selectcountry_1_3>Algeria</selectcountry_1_3></group_1_1>
enter code here<group_1_2><main_doc/><name_doc1>gdgf gfh f</name_doc1><sex_doc1>Male
</sex_doc1><name_institution_1>fsdgdfg</name_institution_1><address_institution_1>gdgfdgfd
</address_institution_1>....';
$_docMapper = new Model_Mapper_XMLDoc();
$_docModel = new Model_XMLDoc();
$_docModel ->doc_data = Zend_Json::encode($_docData);
if ($_docId != 0) {
$_docModel->id = $_docId;
$_docMapper->update($_docModel->toArray(), 'id = ' . $_docId);
$_action = 'update';
} else {
$_docMapper->insert($_docModel->toArray());
$_lastId = $_docMapper->getAdapter()->lastInsertId(); //gets the id of the last inserted record
$_action = 'add';
}
$this->_helper->json->sendJson(array(
'message' => 'success',
'id' => $_lastId,
'action' => $_action
));
It is stored in the db:
INSERT INTO crpcoreix.tbl_xml_doc (slm_data, web_gis_fk) VALUES ('"<SLM_form_v2 id=\\"slmform\\"><group_1_1><section1_1\\/><name1_1>sdfds<\\/name1_1><localname1_2\\/><selectcountry_1_3>Algeria<\\/selectcountry_1_3><\\/group_1_1><group_1_2><main_doc\\/><name_doc1>gdgf gfh f<\\/name_doc1><sex_doc1>Male<\\/sex_doc1><name_institution_1>fsdgdfg<\\/name_institution_1><address_institution_1>gdgfdgfd gdgf<\\/address_institution_1>...', null);
When I'm trying to read the data from the database and display the encoded xml tags the output miss the first part ("<SLM_form_v2 id=\\"slmform\\"><group_1_1><section1_1\\/><name1_1>...) the first part
Array
(
[id] => 1
[xml_data] => "sdfds<\/name1_1>Algeria<\/selectcountry_1_3>...'
[web_gis_fk] =>
)
Please advice how to fix and if there is a better way to store xml documents in database.
Thanx,
first is first you need to double check your given xml syntax, whether its correct or not.
Zend_Json includes a static function called Zend_Json::fromXml(). so
you would better manage to use it instead of Zend_Json::encode when
you encode XML
This function will generate JSON from a given XML input.
This function takes any arbitrary XML string as an input parameter. It also takes an optional Boolean input parameter to instruct the conversion logic to ignore or not ignore the XML attributes during the conversion process.
If this optional input parameter is not given, then the default behavior is to ignore the XML attributes. This function call is made as shown below:
$jsonContents = Zend_Json::fromXml($xmlStringContents, true);
Give it a try but again check your XML syntax
Related
I' creating solr document via solarium plugin in php.
But the all document is stored text_general data type except id field. text_general is the default datatype in solr system.
My doubt is why id field is only to stored string type as default.
And If any possible to add document with string type using solarium plugin.
My code part is here,
public function updateQuery() {
$update = $this->client2->createUpdate();
// create a new document for the data
$doc1 = $update->createDocument();
// $doc1->id = 123;
$doc1->name = 'value123';
$doc1->price = 364;
// and a second one
$doc2 = $update->createDocument();
// $doc2->id = 124;
$doc2->name = 'value124';
$doc2->price = 340;
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1, $doc2));
$update->addCommit();
// this executes the query and returns the result
$result = $this->client2->update($update);
echo '<b>Update query executed</b><br/>';
echo 'Query status: ' . $result->getStatus(). '<br/>';
echo 'Query time: ' . $result->getQueryTime();
}
The result document for the above code is here,
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"*:*",
"_":"1562736411330"}},
"response":{"numFound":2,"start":0,"docs":[
{
"name":["value123"],
"price":[364],
"id":"873dfec0-4f9b-4d16-9579-a4d5be8fee85",
"_version_":1638647891775979520},
{
"name":["value124"],
"price":[340],
"id":"7228e92d-5ee6-4a09-bf12-78e24bdfa52a",
"_version_":1638647892102086656}]
}}
This depends on the field type defined in the schema for your Solr installation. It does not have anything to do with how you're sending data through Solarium.
In the schemaless mode, the id field is always set as a string, since a unique field can't be tokenized (well, it can, but it'll give weird, non-obvious errors).
In your case i'd suggest defining the price field as an integer/long field (if it's integers all the way) and the name field as a string field. Be aware that string fields only generate hits on exact matches, so in your case you'd have to search for value124 with exact casing to get a hit.
You can also adjust the multiValued property of the field when you define the fields explicitly. That way you get only the string back in the JSON structure instead of an array containing the string.
I have this odd problem, I have to read XML structure stored on a mySQL database, one like this:
<geocercaPoligonal>
<nombreGeocerca>Kennedy</nombreGeocerca>
<longitud>-79.89726930856705</longitud>
<latitud>-2.1599807309506396</latitud>
<longitud>-79.9029341340065</longitud>
<latitud>-2.172760363061884</latitud>
</geocercaPoligonal>
When I get the query on PHP (using PDO Fetch:Assoc) and output the result, it results on this:
' Kennedy -79.89726930856705 -2.1599807309506396 -2.172760363061884 -79.9029341340065 '
All tags are omitted and this leads to error when reading this data, I must get values from specific tags, I get a XML load string
The DB::getRow its a prepare/execute PDO function
$geocerca = DB::getRow('SELECT * FROM GeocercasxUsuario WHERE IdGeocerca = :IdGeocerca', ['IdGeocerca' => $IdGeocerca]);
$infoXML = simplexml_load_string($geocerca['InformacionGeografica']);
//The field from the database with the XML string
It gets this info
SimpleXMLElement::__set_state(array(
'nombreGeocerca' => 'Kennedy',
'longitud' => array(
0 => '-79.89726930856705',
1 => '-2.172760363061884',
),
'latitud' => array(
0 => '-2.1599807309506396',
1 => '-79.9029341340065',
),
))
It doesn't read the XML structure properly, how could I fix this? It's something from PHP or mySQL?
What in particular is not being read properly? The SimpleXML object contains all the data from your XML.
You can convert the object into an array so it is easier to work with as follows:
$json_string = json_encode($infoXML);
$result_array = json_decode($json_string, TRUE);
After trying some things, I switched my select statement to get specific XML data like this:
Instead of
SELECT * FROM GeocercasxUsuario WHERE IdUsuario = n (just for example)
I changed it to
SELECT ExtractValue(InformacionGeografica,'/geocercaPoligonal/latitud') AS Latitud, ExtractValue(InformacionGeografica,'/geocercaPoligonal/longitud') AS Longitud, ...(other fields)... FROM GeocercasxUsuario WHERE IdUsuario = n
This way I get an XML array of the values of each tag, pretty useful if you only want inner values :)
I am having troubles converting a string which contains tab delimited CSV output
into an array. While using the following code :
$data = stream_get_contents($request->getShipmentReport());
I get back data as following:
Date Shipped Comments Feedback Arrived on Time
5/11/15 2 comment response Yes
Now I would like to process this data into an array with the returned headers(line 1) as the index containing the value for each line which follows after that.
I am trying to end up with something like this :
$line['Date'] = 5/11/15
$line['Shipped'] = 2
$line['Feedback'] = response
$line['Arrived on Time'] yes
What would be the best way to achieve this ?
I recommend using a library for handling CSV for example the CSV-Package by The League of Extraordinary Packages
You can pass your data and start working with array structures right away:
$csvString = stream_get_contents($request->getShipmentReport());
$csvReader = \League\Csv\Reader::createFromString($csvString);
$data = $csvReader->fetchAssoc(
array('Date', 'Shipped', 'Comments', 'Feedback', 'Arrived on Time')
);
// Or since line 0 contains header
$data = $csvReader->fetchAssoc(0); // 0 is offset of dataset containing keys
Now your data should be in a structure like:
$data = array(
array(
'Date' => '5/11/15',
'Shipped' => '2',
...
),
array(
...
)
);
You can even filter out specific datasets and all kinds of fancy stuff. Just check the documentation I linked to.
League CSV reader gives me a bad result. I use this instead:
$csvReportString = stream_get_contents($request->getReport());
$csvReportRows = explode("\n", $csvReportString);
$report = [];
foreach ($csvReportRows as $c) {
var_dump($c);
if ($c) { $report[] = str_getcsv($c, "\t");}
}
var_dump($report);
Not an experienced developer and using CodeIgniter for the first time. I'm trying to grab a signed URL for a given MP3 filename stored in S3. This is currently working with the exception of files that contain brackets.
Relevant controller code:
function index ($streamfile) {
// Load S3 client
$this->load->spark('amazon-sdk');
$s3 = $this->awslib->get_s3();
// Define request parameters
$s3bucket = $userdata['s3bucket']; // defined elsewhere
$streamfiletest = ($string)'Crazy_(Remix).mp3';
// Request signed URL
$url = $s3->get_object_url($s3bucket, ***EITHER $streamfiletest or $streamfile***, '5 minutes');
// Fetch status code
$http = new CFRequest($url);
$http->add_header('Content-Type', '');
$http->send_request(true);
$code = $http->get_response_code();
$headers = $http->get_response_header();
// Load the view
$data['filename'] = $url;
$data['debug'] = array(
'file1' => $streamfile,
'file2' => $streamfiletest,
'signed_url' => $url,
'code' => $code,
'headers' => $headers
);
$this->load->view('play', $data);
Relevant view code:
<?php if (isset($debug)) {
echo "DEBUGS:";
echo '<pre>' . print_r($debug, TRUE) . '</pre>';
} ?>
As you can see I either pass $streamfile or $streamfiletest. In the debug I can confirm that both variables are the same string.
When passing $streamfile to the URL request, the URL in the response is incorrect:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%26%2340%3BRemix%26%2341%3B.mp3?AWSAccessKey...
[code] => 404
You can see that the brackets have been strangely encoded %26%2340%3B and therefore I can't find the file in S3.
When passing $streamfiletest however, the response is fine:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%28Remix%29.mp3?AWSAccessKey...
[code] => 200
The brackets are encoded correctly in the signed URL an I get a HTTP 200 from S3.
Any ideas what could be causing this?
In the debug I can confirm that both variables are the same string
Actually, not quite.
If you look closely, it becomes apparent what the url escaped values must mean:
%26%2340%3B %26%2341%3B
& # 40 ; & # 41 ;
Those are numeric html character codes that the browser will display as ( and ) but it does not in fact mean that the two strings have identical content. They only appear to.
The solution, of course, depends on how they are getting transformed that way, and either not doing that, or decoding the numeric character codes.
Try doing the following to decode the url encoded brackets
$data['filename'] = urldecode($url);
This should return the string to its expected format ie with brackets
I'm having trouble populating a combobox from an XML response. Here is the XML that I am receiving:
<distros>
<entry>
<distro>CentOS</distro>
<distro>Debian</distro>
<distro>Other</distro>
<distro>Sabayon</distro>
<distro>Ubuntu</distro>
<distro>VMware</distro>
<distro>Windows</distro>
</entry>
</distros>
So probably the most basic form of XML ever!
and here is the flex code:
private function getDistros():void
{
httpReq = new HTTPService;
httpReq.url = 'http://myserver/xml.php';
httpReq.resultFormat = 'e4x';
httpReq.method = 'GET';
httpReq.addEventListener(ResultEvent.RESULT, popDistros);
httpReq.send( null );
}
private function popDistros(event:ResultEvent):void
{
if(event.result != "")
{
// Set the data to the XMLListCollection for lookup
myXmlCollection= new XMLListCollection(event.result.entry);
// Bind the ListCollection to the comboBox
Alert.show(myXmlCollection.toString());
distroCombo.dataProvider = myXmlCollection.toString();
}
}
and the MXML:
<mx:ControlBar x="139" y="10" width="266" height="358" verticalAlign="top" horizontalAlign="left" direction="vertical">
<mx:ComboBox id="distroCombo" labelField="distro"></mx:ComboBox>
<mx:ComboBox id="imageCombo"></mx:ComboBox>
<mx:Button label="Download"/>
</mx:ControlBar>
The XML comes back fine in the Alert but the comboBox won't populate and I have tried this so many different ways now, anyone got any suggestions? Have I just been staring at it far too long?
if the result (event.result) is XML, then It should wotk like this: (it differs with .distro in the end compared to yours)
myXmlCollection = new XMLListCollection(event.result.entry.distro);
...this should create valid data in myXmlCollection
But then also this row is wrong:
distroCombo.dataProvider = myXmlCollection.toString();
it creates just one item in dataProvider of type string, (Just BTW: if you would have used spark combobox, you would have get compile error at this row).
just use this instead:
distroCombo.dataProvider = myXmlCollection;
And also note, that you can see correct result in the Alert, but it does not say if the data are of correct type, coz Alert evertyhing converts to string :)