Get complete XML structure stored on mySQL - php

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 :)

Related

How can print a json response with php

I'm building a simil web-service in php. This web service can read all record from a table of database and return a list of it in json format.
This is the code of my getArticoli.php file:
<?php
require_once('lib/connection.php');
$query_Articolo = "SELECT CodArticolo,NomeArticolo,Quantita,CodiceBarre, PrezzoAttuale, PrezzoRivenditore,PrezzoIngrosso
FROM VistaArticoli ";
$result_Articoli = $connectiondb->query($query_Articolo);
$answer = array ();
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = ["id" => $row_Articoli['CodArticolo'],
"nome" => '"' . $row_Articoli['NomeArticolo'] . '"',
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']];
}
//echo "fine";
echo json_encode($answer);
?>
Now, if I try to open this page, with this url: http://localhost/easyOrdine/getArticoli.php
I don't get the json_response.
In the table of database, there are 1200 records. If I try to insert an echo message in while cycle, I see it.
I have noticed that the problem lays with this field:
"nome"=>'"'.$row_Articoli['NomeArticolo'].'"'
If I remove this field from the response, I can correctly see the json response.
In this field there are any character from a-z/0-9 and special character like "/ * ? - and other".
It is possible that these special character can cause any error of the json answer?
EDIT
I have limit at 5 my query and this is the response:
[{"id":"878","0":"ACCESSORIO PULIZIA PUNTE DISSALDANTE 3 MISURE","quantita":"1","codiceBarre":"DN-705100","codartFornitore":"DN-705100","PrezzoAttuale":"14.39","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"318","0":"ACCOPPIANTORE RJ11 TELEFONICO VALUELINE VLTP90920W","quantita":"20","codiceBarre":"5412810196043","codartFornitore":"5412810196043","PrezzoAttuale":"0.68","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"320","0":"ACCOPPIATORE AUDIO RCA VALUELINE VLAB24950B","quantita":"5","codiceBarre":"5412810214136","codartFornitore":"5412810214136","PrezzoAttuale":"1.29","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"310","0":"ACCOPPIATORE RJ45 VALUELINE VLCP89005W","quantita":"8","codiceBarre":"5412810228843","codartFornitore":"5412810228843","PrezzoAttuale":"0.38","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"311","0":"ACCOPPIATORE USB2 VALUELINE VLCP60900B","quantita":"5","codiceBarre":"5412810179596","codartFornitore":"5412810179596","PrezzoAttuale":"1.80","prezzoRivenditore":null,"prezzoIngrosso":null}]
First, remove those extraneous quote characters. You don't need them and they could hurt you down the road:
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = [
"id" => $row_Articoli['CodArticolo'],
"nome" => $row_Articoli['NomeArticolo'],
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']
];
}
Then, run your query as is (without the LIMIT), and afterwards run echo json_last_error_msg()';, which could give you a hint to what's going on.
Also, being that your DB is in italian, maybe its encoding is not UTF-8. json_encode requires UTF-8 encoded data. So you may try to utf8_encode your article names before json_encoding the array:
"nome" => utf8_encode($row_Articoli['NomeArticolo']),
And see what you get.
Changing your DB charset to 'utf8mb4' could do the trick as well, and it is usually recommended.

Save xslt form in mysql using zend 1.12

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

XML parsing with XPath and PHP handle empty values

while parsing through a XML tree like this:
<vco:ItemDetail>
<cac:Item>
<cbc:Description>ROLLENKERNSATZ 20X12 MM 10,5 GR.</cbc:Description>
<cac:SellersItemIdentification>
<cac:ID>78392636</cac:ID>
</cac:SellersItemIdentification>
<cac:ManufacturersItemIdentification>
<cac:ID>RMS100400370</cac:ID>
<cac:IssuerParty>
<cac:PartyName>
<cbc:Name></cbc:Name>
</cac:PartyName>
</cac:IssuerParty>
</cac:ManufacturersItemIdentification>
</cac:Item>
<vco:Availability>
<vco:Code>available</vco:Code>
</vco:Availability>
</vco:ItemDetail>
I always get a blank space which breaks my CSV structure if cbc:Name is empty, which looks like this:
"ROLLENKERNSATZ 20X12 MM 10,5 GR.";78392636;;RMS100400370;"";available
The "available" string is in a new line so my CSV is not structered any more.
My XPath array looks like this:
$columns = array('Description' => 'string(cac:Item/cbc:Description)',
'SellersItemIdentification' => 'string(cac:Item/cac:SellersItemIdentification/cac:ID)',
'StandardItemIdentification' => 'string(cac:Item/cac:StandardItemIdentification/cac:ID)',
'Availability' => 'string(vco:Availability/vco:Code)',
'Producer' => 'string(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty/cac:PartyName/cbc:Name');
Is there any expception or replacement I can handle with like replacing the empty node value with "no producer" or something like this?
Thank you
If the value to use as the 'default' can somehow be made to exist somewhere in your input document, the problem can be solved with a quasi-coalesce like this:
e.g.
<vco:ItemDetail xmlns:vco="x1" xmlns:cac="x2" xmlns:cbc="x3">
<ValueIfNoProducer>No Producer</ValueIfNoProducer>
<cac:Item>
...
Then this Xpath 1.0 will apply a default if the Name element is empty or whitespace:
(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty
/cac:PartyName/cbc:Name[normalize-space(.)] | ValueIfNoProducer)[1]
I think the following is possible directly in XPath 2.0, but I stand to be corrected:
(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty
/cac:PartyName/cbc:Name[normalize-space(.)] | 'No Producer')[1]

PHP array custom format

I am just starting on the PHP.
I am working on getting information from WordPress database.
The plugin writes data to a DB, from the Sign up form.
What I want is to get this data formatted on my own way, let's say a table, on a separate page.
So what I did already, is to connect to a DB, and print the data. Did it by this:
<?php
//connect to the database
mysql_connect ("host","user","pasw") or die ('Cannot connect to MySQL: ' . mysql_error());
mysql_select_db ("database") or die ('Cannot connect to the database: ' . mysql_error());
//query
$query = mysql_query("select id, data from wp_ninja_forms_subs") or die ('Query is invalid: ' . mysql_error());
//write the results
while ($row = mysql_fetch_array($query)) {
echo $row['id'] . " " . $row['data'] . "
";
// close the loop
}
?>
The thing is, that I get the results, which doesn't really suit me:
14 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:8:"John Doe";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+3706555213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 1";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" Finansiniai ";}}} 15 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:10:"Bill Gates";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+5654412213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 2";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}} 16 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:7:"Person3";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:7:"6463213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 3";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:2:{i:0;s:10:" HTML/CSS ";i:1;s:12:" Photoshop ";}}} 17 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:11:"Pretty Girl";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:9:"643122131";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:4:"Zara";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}}
Now, what I want to see is a table:
2013.10.25 Pretty Girl 643122131 Zara Įvaizdžio
2013.10.25 Person3 6463213 Company 3 HTML/CSS , Photoshop
2013.10.25 Bill Gates +5654412213 Company 2 Įvaizdžio
2013.10.25 John Doe +3706555213 Company 1 Finansiniai
Could someone tell me, how to achieve that?
I believe, that my data output is an array, or am I wrong about it too?
If yes, maybe someone could give me an example how to format one part of that array, so I could do the rest?
Or even some hint on what to google for?
Thanks!
Use "\n" for new line character :)
Your individual values (a:4:{i:0....}) have been "serialized". This one was an array of four elements that was passed to the serialize() PHP function. The function returned it's textual representation (i.e. it has "serialized" the array). So you have the entire array saved in one cell in database as simple text.
Function unserialize() does the opposite - turns the "serialized" (text) values and returns the original PHP object (an array in this case).
You can serialize almost any PHP object as long as it doesn't have some any "resources" attached to it. But there is already a separate question for that: What could cause a failure in PHP serialize function?
As long as you serialize arrays of numbers, strings and arrays and even simple objects there is nothing to worry about.
Your first cell (no 14) when unserilalized:
array (
0 =>
array (
'field_id' => 2,
'user_value' => 'John Doe',
),
1 =>
array (
'field_id' => 4,
'user_value' => '+3706555213',
),
2 =>
array (
'field_id' => 12,
'user_value' => 'Company 1',
),
3 =>
array (
'field_id' => 8,
'user_value' =>
array (
0 => ' Finansiniai ',
),
),
)
(Using: http://www.functions-online.com/unserialize.html) Run these trough a for loop or something to get the rendering you need, that's up to you.

PHP-generated JSON for Google Maps: a tiny mystery

I am using a PHP script (this one) to generate a JSON file for a Google Map.
this is the PHP code (note: I am using Laravel):
<?php
$query = "SELECT id, info, lat, lng FROM places";
$results = DB::select($query);
$myLocations = array();
$i = 0;
$testLoc = array('loc95' => array( 'lat' => 15, 'lng' => 144.9634 ));
foreach ($results as $result)
{
$myLocation = array(
'loc'.++$i => array(
'lat' => round((float)$result->lat, 4),
'lng' => round((float)$result->lng, 4)
));
$myLocations += $myLocation;
}
$myLocations += $testLoc;
echo json_encode($myLocations);
?>
and this is the output:
{"loc1":{"lat":45.4833,"lng":9.1854},"loc2":{"lat":45.4867,"lng":9.1648},"loc3":{"lat":45.4239,"lng":9.1652},"loc95":{"lat":15,"lng":144.9634}}
ok. the script I use to put the JSON data in a Google Map, unfortunately, keeps ignoring any data coming from the MySQL database, and shows only the test data place(s). I have tried to swap data, to put in test data the same info found in database... nothing, I keep seeing only the test data.
but, really: I cannot figure out why. What am I missing... ?
You wrote that you're using another script and that the other script only shows the testlocations on google maps.
My guess is that you didn't update the other script to your needs, specifically my crystal ball is telling me that you still have this line in there:
setMarkers(locs);//Create markers from the initial dataset served with the document.
In your question you only showed the part which worked and I agree, but you only mentioned that "something else" isn't working. If you want an answer for that part, try reprashing your question and include the parts which cause you problems.

Categories