Add white space after each xml element usinh php - php

I have created a xml from an array using php.The result is listed below.
<Mst><Mstrow><sCode>10</sCode>Test<sName></sName></Mstrow></Mst>
But I want to show this xml with white spaces between each element lik this
<Mst> <Mstrow> <sCode>10</sCode> <sName>Test</sName> </Mstrow> </Mst>
Below is my code ,
$results = Array ( [0] => Array ( [sCode] => 10 [sName] => Test) ) ;
$main = $dom->appendChild($dom->createElement('Mst'));
if($results != Array()){
foreach ($results as $datas) {
$row ->$main->appendChild($dom->createElement('Mstrow'));
foreach ($datas as $name => $value) {
$row
->appendChild($dom->createElement($name))
->appendChild($dom->createTextNode($value));
}
}
}
Please provide a solution

I may have missunderstood the qn, and I assume in your (pre) example test should be between <sName> tags. I would have thought a simple string replace before you echo/save your XML string would do the trick?
e.g.
echo str_replace( '><' , '> <', $myXml->asXML());

Related

How to make key value by explode and arrange matching key values into one key?

I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!

php get the text into an array list

I have an array in the database. When I used print_r($variable_name), I got the array like this
Array
(
[0] => Array
(
[attribute_name] => Disk space,Color,Processor
)
)
So to get the value of attribute_name I tried this
foreach($attributes_name as $key=>$val) {
echo $val['attribute_name'];
}
Here I got the result like Disk space,Color,Processor. But I want the result should come like a list
<li>Disk Space</li>
<li>Color</li>
<li>Processor</li>
So can someone tell me how to do this?
Try this :
<?php
$arr = array(array("attribute_name" => "Disk space,Color,Processor"));
foreach($arr as $val) {
$resultArr = explode(",",$val['attribute_name']);
foreach($resultArr as $value){
echo "<li>".$value."</li>";
// Add id in li
echo "<li id='".str_replace(" ","_", strtolower($value))."'>".$value."</li>";
}
}
?>

Copy array into another array in PHP

I am trying to copy array into another array in PHP. Then send the response as JSON output. But it copies only the last element in array multiple times. Please let me know where I am going wrong? Any help is appreciated
PHP code
stmt_bind_assoc($stmt, $resultrow);
while ($stmt->fetch()) {
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Output from print_r($resultrow).This is correct. Values in array is different
Array( [a_id] => 1 [b_number] => 10101010 [dateandtime] => 2013-12-25 09:30:00 )
Array( [a_id] => 1 [b_number] => 20202020 [dateandtime] => 2013-12-27 11:40:00 )
Output from json_encode($r).This is incorrect. Values in array is same
[{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"},
{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"}]
You got the function stmt_bind_assoc from here: http://www.php.net/manual/en/mysqli-stmt.fetch.php#82742
Posted under that OP is:
"...the problem is that the $row returned is reference and not data.
So, when you write $array[] = $row, the $array will be filled up with
the last element of the dataset."
With that user's solution I came up with this to resolve your issue:
// replace your posted code with the following
$r = array();
// loop through all result rows
while ( $stmt->fetch() ) {
$resultrow = array();
foreach( $row as $key=>$value )
$resultrow[ $key ] = $value;
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Next time you get code from a source read the comments about the source.

Different Array Values depending on the if statement

I am building a web crawler which scans links, titles and meta descriptions from links that are found from one url submitted
This if statement i think is correct. $description is the variable which holds all the descriptions from the array $link. But i notice not all sites have a meta description (wikipedia for example) so i have decided that i would like the first twenty characters to act as the description if the description is empty. (By the way, the function and calling of everything works, i just wanted you to see it)
if ($description == '') {
$html = file_get_contents($link);
preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
$res = get_custom_excerpt($re[1]);
echo "\n";
echo $res;
echo "\n";
}
However, in the array, the links are stored in [link], the title of the link in [title] and the description in [description]. But i don't know how i would cope with adding $res to my array and to only use if the if statement works.
$output = Array();
foreach ($links as $thisLink) {
$output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
}
print_r($output);
You can use array_push() to add $res back to your array and then evaluate the array however you need to; not 100% sure what you're trying to do...
From your wording I think you want to do this:
$outputs = array();
foreach ($links as $thisLink) {
$output = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink));
if ($output['description'] == null) {
$output['description'] = getMetas($res);
}
$outputs[] = $output;
}
You might want to adjust the if statement because I do not know what getMetas() returns when there is not description.

PHP: (PDO) Mysql most effective way to add sting to returned value out of db

In a mysql database I store some image names without the exact path.
So what I like to do is add the path before I load the returned array into jQuery (json) to use it in the JQ Galleria plugin.
In the columns I've got names likes this:
11101x1xTN.png 11101x2xTN.png 11101x3xTN.png
Which in the end should be like:
./test/img/cars/bmw/11101/11101x1xTN.png
./test/img/cars/bmw/11101/11101x2xTN.png
I could just add the whole path into the database but that seems 1. a wast of db space. 2. Then I need to update he whole db if the images path changes.
I could edit the jQuery plugin but it doesn't seem practical to update the source code of it.
What is the right thing to do and the fasted for processing?
Can you add a string after you make a db query and before you fetch the results?
part of the function where I make the query:
$needs = "thumb, image, big, title, description";
$result = $get_queries->getImagesById($id, $needs);
$sth=$this->_dbh->prepare("SELECT $needs FROM images WHERE id = :stockId");
$sth->bindParam(":stockId", $id);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
this is the foreach loop:
$addurl = array('thumb', 'image', 'big');
foreach ($result as $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
}
}
}
the array looks like this:
Array
(
[0] => Array
(
[thumb] => 11101x1xTN.png
[image] => 11101x1xI.png
[big] => 11101x1xB.png
[title] => Title
[description] => This a blub.
)
)
The url should be add to thumb, image and big.
I tried to change the array values using a foreach loop but that didn't work. Also not noting if the use of that would course a unnecessary slowdown.
well, you almost nailed it. only thing you forgot is to store your $val back in array.
foreach ($result as $i => $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
$result[$i][$item] = $val;
}
}
}
however, I'd make it little shorter
foreach ($result as $i => $array) {
foreach ($addurl as $item) {
$result[$i][$item] = '/test/img/cars/bmw/11101/'.$array[$item];
}
}
}
Assuming your array looks like this:
$result = array("11101x1xTN.png", "11101x2xTN.png", "11101x3xTN.png");
A simple array_map() can be used.
$result_parsed = array_map(function($str) { return './test/img/cars/bmw/11101/'.$str; }, $result);
As seen Here

Categories