PHP SimpleXML Load File with Null elements - simplexml

I have the following XML file called 'cookie_domain.xml' with the contents:
<?xml version="1.0" encoding="UTF-8"?>
<setting>
<parameter>cookie_domain</parameter>
<displayname>Cookie Domain</displayname>
<grouping>Sessions</grouping>
<selecttype>text</selecttype>
<setting />
<help>Domain that the cookie is valid for</help>
</setting>
which I load into an object using:
$xml_object = simplexml_load_file('cookie_domain.xml');
The problem is that I want the 'setting' element to be null as specified in the XML, but what I get from the object, when I turn it into an array, is:
Array
(
[parameter] => cookie_domain
[displayname] => Cookie Domain
[grouping] => Sessions
[selecttype] => text
[setting] => SimpleXMLElement Object
(
)
[help] => Domain that the cookie is valid for
)
Is there anyway to get SimpleXML to honour the 'null' value instead of putting a 'SimpleXMLElement Object' in there? So I would end up with:
Array
(
[parameter] => cookie_domain
[displayname] => Cookie Domain
[grouping] => Sessions
[selecttype] => text
[setting] =>
[help] => Domain that the cookie is valid for
)
I am using this information to import into a database and the Object is causing issues as I need the element to be there, even if it is 'null' as this is valid in my application.
Thanks very much,
Russell

In XML, a self-closing element (e.g. <foo />) is equivalent to one with empty contents (e.g. <foo></foo>) so if you want this to translate as a php NULL value, you will have to check for the contents being an empty string.
A simple way of getting what you want given the example you've posted would be to loop over every element in the document setting an array key to the appropriate string, and replacing empty strings with NULL:
$settings_array = array();
foreach ( $xml_object->children() as $tag_name => $element )
{
$settings_array[$tag_name] = trim( (string)$element );
if ( strlen($settings_array[$tag_name]) == 0 )
{
$settings_array[$tag_name] = NULL;
}
}
Here is a live demo.

Related

Smarty: How to get value of array in Object

I have an array inside an object inside an array in my smarty template. A simplified example below, but using the same structure.
Array (
[product] => ModelView Object (
[model:protected] => Model Object (
[id] => 1234
)
)
)
How can I get [id]?
I can get the 'product' object to appear on the page as an array using:
$this->get_template_vars('product')
But from there I can't seem to narrow it down to only get the [id].
Apparently all it takes is a post on stackoverflow and then you try one more thing after hours and it works.
My solution below.
{php}
$id = $this->get_template_vars('product');
$id = $id->id;
{/php}

xpath get node from inside value

Current xpath: Product/ProductMultimediaObject/MultimediaObject
Returns:
Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ContentType] => application/pdf
[Date] => 2014-11-01 01:20:35
[Description] => Leaflet
)
)
)
But I'm currently just hoping that the found MultimediaObject is the correct one - which is not. I need to get the MultimediaObject where Description has a specific value.
What I've tried:
Product/ProductMultimediaObject/MultimediaObject[Description/text() = 'WhatIWant']
Product/ProductMultimediaObject/MultimediaObject/Description[text() = 'WhatIWant']
Your Desciption is an attribute. Try
Product/ProductMultimediaObject/MultimediaObject[#Description = 'WhatIWant']
or, for short,
//MultimediaObject[#Description = 'WhatIWant']

codeigniter session values lost on second page

I have lengthy search form and i am trying to keep the form values in session. I use codeigniter pagination, so i need to store the values entered in the search form in the session (i am trying to avoid storing them in the database)
This problem bother me couple of days and i am unable to solve it. Here is the code. For the sake of clarification i provide the comments for each line of my code:
// my submit button named search_button has been clicked
if ($this->input->post('search_button')) {
// all the values from the form are stored in array
$formValues = $this->input->post(NULL, TRUE);
// i assign the values of $formValues array to session
$this->session->set_userdata('formValues', $formValues);
// i store the values in local variable
$mySessData = $this->session->userdata('formValues');
// i count the values of the $formValues to be sure how many fields i get back
// reason for that is that my form is built dynamically
// returns 19 if the form has been submitted.
// when i submit the form, i get 19
echo "Count of form values is now: " . count($formValues);
// i print the $formValues array, to be sure that it return the form values
// and yes, it does if the form has been submitted.
// see the $formValues returns section bellow to see what is returned
echo "<pre>";
print_r($formValues);
echo "</pre>";
// i print my local variable to ensure that variable $mySessData is not empty
// see the section $mySessData retruns (1) to see returned values
echo "Confirm that sess data has been set up";
echo "<pre>";
print_r($mySessData);
echo "</pre>";
} else {
// else, means that form has not been submitted but that controller has been called from the next link
// in the pagination links. This always return empty array, that is nothing...
echo "<pre>";
print_r($mySessData);
echo "</pre>";
}
If the form has been submitted, the $formValues returns the following:
Array
(
[addtypeid] =>
[isnew] =>
[orderby] =>
[geographicareaid] =>
[catid] => 1
[catid2] =>
[manufacturerid] =>
[modelid] =>
[yearofmanufacturing_from] =>
[yearofmanufacturing_to] =>
[hoursused_from] =>
[hoursused_to] =>
[horsepowers_from] =>
[horsepowers_to] =>
[price_from] =>
[price_to] =>
[colorid] =>
[isdamaged] =>
[search_button] => Submit‚
)
My variable $mySessData returns the very same dataif the form has been submitted:
Array
(
[addtypeid] =>
[isnew] =>
[orderby] =>
[geographicareaid] =>
[catid] => 1
[catid2] =>
[manufacturerid] =>
[modelid] =>
[yearofmanufacturing_from] =>
[yearofmanufacturing_to] =>
[hoursused_from] =>
[hoursused_to] =>
[horsepowers_from] =>
[horsepowers_to] =>
[price_from] =>
[price_to] =>
[colorid] =>
[isdamaged] =>
[search_button] => Submit‚
)
And on the end, if i click on pagination link
$config['base_url'] = site_url('/searchresults/display/'.$limit.'/');
, which point to the same controller and same method, well..i get an empty array.
Any help will be appreciated.
Regards, John
I think It would be better if use method="get" in your form. posting your form with get instead of post would be more preferable in case of search form as u wont need to maintain any session and no need of storing values in database also. you can easily access a feild anytime using
$this ->input->get('fild_name');
You can optimize your code this way and you dont need to maintain session variables as you will always have the search feild valies in your url. Using session another problem is with unsetting the session variable.
I personally dont think that creating a session variable just to maintain pagination is not a good idea.Moreover in a search form there is no need of security so you can send your form using "get" insted of "post"

Joomla 1.5 can't save component parameters

I have custom coded Joomla v1.5 component. In administrator zone I change its parameters, but when I taking param values in my code I get only default values, but not the new as I set in components admin zone params window.
global $option;
$params = &JComponentHelper::getParams( $option );
print_r($params);
The output looks like this:
JParameter Object
(
[_raw] => param_1=This is changed value of the param 1
param_2=20
param_3=This is changed value of the param 3
[_xml] =>
[_elements] => Array
(
)
[_elementPath] => Array
(
[0] => /home/x/domains/xyz.com/public_html/libraries/joomla/html/parameter/element
)
[_defaultNameSpace] => _default
[_registry] => Array
(
[_default] => Array
(
[data] => stdClass Object
(
[param_1] => some default value 1
[param_2] => 10
[param_3] => some default value 3
)
)
)
[_errors] => Array
(
)
)
How you in output, param raw data changes, but the data field does not. So what's the problem ? Any ideas ?
I've found out the problem. So when I create a menu link to my component view, it duplicates the component parameters in menu item params list. So it overrides the main component parameters. That's why if I change param value in components param window(in admin zone), I get only param values that are in menu items window. Also found some more information about it in Joomla forum: http://forum.joomla.org/viewtopic.php?f=304&t=485837

Simplexml How to access all element of the same node

[Villa] => Array
(
[0] => SimpleXMLElement Object
(
[VillaID] => 6
[VillaName] => Mary
[Distances] => SimpleXMLElement Object
(
[Distance] => Array
(
[0] => SimpleXMLElement Object
(
[Destination] => Sea
[Value] => 1000 m
)
[1] => SimpleXMLElement Object
(
[Destination] => Market
[Value] => 800 m
)
)
)
)
[1] => SimpleXMLElement Object
(
[VillaID] => 21
[VillaName] => Marion
[Distances] => SimpleXMLElement Object
(
[Distance] => Array
(
[0] => SimpleXMLElement Object
(
[Destination] => Beach
[Value] => 5 min
)
)
)
)
)
I need to print all, only of 1 villa (example with id = 6) but VillaId is not an array so it's impossible to get all with foreach
I can obtain it with:
echo 'Name of Villa: '.$xml->Villa[0]->VillaName.'';
etc. etc ... but in this way have to change manually for every villa (too much) the value in the brackets.
i've tried with $xml->Villa[$value]->VillaName; ($value comes from another page) but it's not working...
Tanks for help!
First of all, your question starts with "i have this xml:" followed by something that is not XML. I'm not saying this to be a smartass, rather because it's important for XML beginners to understand that print_r() is not the right way to inspect SimpleXMLElements. Sometimes it will show you things that aren't in your XML, other times it will not show things that are actually in your XML. In short: do not use print_r() on SimpleXMLElement. Just use ->asXML() and look at the actual XML.
From what I understand, you want to locate and select a node based on some criteria. XML just happens to have a language for that: XPath. The official specs aren't terribly user-friendly but w3schools.com has a pretty good XPath tutorial.
I need to print all, only of 1 villa (example with id = 6) but VillaId is not an array so it's impossible to get all with foreach
Anywhere in your document, you want to select all Villa nodes with an attribute VillaID whose value is "6". In XPath:
//Villa[#VillaID="6"]
Via SimpleXML:
$xml->xpath('//Villa[#VillaID="6"]');
Attention, xpath() always return an array.

Resources