PHP - simplexml_load_string doesn't work as expected - php

When converting xml to object, everything seems fine according to print_r($result);. But if I use $result->title it returns object instead of string and when looping $result->documents it gets really strange..
$xml = '<return>
<id>65510</id>
<title>SMART</title>
<info/>
<documents>
<name>file_1.pdf</name>
<path>http://www.domain.com/documents/file_1.pdf</path>
</documents>
<documents>
<name>file_2.pdf</name>
<path>http://www.domain.com/documents/file_2.pdf</path>
</documents>
<documents>
<name>file_3.pdf</name>
<path>http://www.domain.com/documents/file_3.pdf</path>
</documents>
</return>';
$result = simplexml_load_string($xml);
print_r($result); /* returns:
SimpleXMLElement Object
(
[id] => 65510
[title] => SMART
[info] => SimpleXMLElement Object
(
)
[documents] => Array
(
[0] => SimpleXMLElement Object
(
[name] => file_1.pdf
[path] => http://www.domain.com/documents/file_1.pdf
)
[1] => SimpleXMLElement Object
(
[name] => file_2.pdf
[path] => http://www.domain.com/documents/file_2.pdf
)
[2] => SimpleXMLElement Object
(
[name] => file_3.pdf
[path] => http://www.domain.com/documents/file_3.pdf
)
)
)
*/
$_VALUE['title'] = $result->title;
print_r($_VALUE); /* returns:
Array
(
[title] => SimpleXMLElement Object
(
[0] => SMART
)
)
*/
foreach ($result->documents as $key=>$value) {
echo $key . "<br/>";
} /* returns:
documents
documents
documents
instead of returning:
1
2
3
*/
I need $result->title to return string and $result->documents to be an array with indexes 1,2,3.

There are difference between print_r and echo in this context. Instead Print try echo
echo (string) $result->title;
It will work and output as SMART
and array
$p = 1;
foreach ($result->documents as $value) {
echo $value->name . "<br/>";
//for key
echo $p++.'</br>';
}

Related

Operations on the table - SimpleXMLElement Object

How to display one element/object = LAT from this array and save it to a variable.
<?php
$url = "XML";
$xml = simplexml_load_file($url);
print_r($xml);
?>
//echo $xml->LAT;
//$value = (string) $xml->row[0]->LAT;
//echo $value;
Response fields XML:
SImpleXMLElement Object ( [row] => SimpleXMLElement Object ( [#attributes] => Array ( [MA] => 310627000 [LAT] => 9.967386 [LON] => 76.269330 ) ) )
I will be grateful for your help.
Problem solved.
echo $xml->row[0]['LAT'] . "<br>";

convert json string into php object and access it's value

I have json data as shown in the picture below, how do I get highlighted value and change them?
Json Data
EDITED
I try to get the "furniture_id" using the code below...but fails...I don't know what else i can do to get the value
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
foreach ($test as $key => $value) {
dd($furniture_id['id']);
}
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
$response=json_decode($test);
foreach ($response->data as $key => $value) {
echo $value->furniture_id;
echo "<br>";
}
first you have to decode json data using json_encode method.Then if you print json decode response then you will be get an result of standard object
stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[owned_id] => 1
[furniture_id] => 1
[owned_name] => desk_123
)
[1] => stdClass Object
(
[owned_id] => 2
[furniture_id] => 2
[owned_name] => chair_123
)
[2] => stdClass Object
(
[owned_id] => 3
[furniture_id] => 4
[owned_name] => sofa_123
)
)
)
Updated
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
$response=json_decode($test);
echo "<pre>";
print_r($response);
$newArray=[];
foreach ($response->data as $key => $value) {
$row=[];
$value->furniture_id= $value->furniture_id+1;
}
echo "<pre>";
print_r($response->data);
Now output will be
Array
(
[0] => stdClass Object
(
[owned_id] => 1
[furniture_id] => 2
[owned_name] => desk_123
)
[1] => stdClass Object
(
[owned_id] => 2
[furniture_id] => 3
[owned_name] => chair_123
)
[2] => stdClass Object
(
[owned_id] => 3
[furniture_id] => 5
[owned_name] => sofa_123
)
)
Try this code
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
$test = json_decode($test, true);
//if you want to change value of furniture_id in index 0
$test['data'][0]['furniture_id'] = 111;
print_r($test); exit;
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
this $test string itself is a json string.As json is similar to javascript object, there is no way to to store json as we can do in javascript.That's why we put json inside a quote in php and represent them as string.
what you can do is turn the json string into a php object using json_decode() and access them in foreach loop
foreach (json_decode($test)->data as $key) {
echo $key->furniture_id;
}

XML into MySql Database (SimpleXML)

I've this XML file taked from post method :
<?xml version="1.0" encoding="utf-8"?>
<impianto id="id1">
<misure>
<misura time="1900-01-01T01:01:01+01:00" quantita="1"/>
<misura time="0001-01-01T00:00:00+01:00" quantita="-79228162514264337593543950335"/>
<misura time="9999-12-31T23:59:59.9999999+01:00" quantita="79228162514264337593543950335"/>
</misure>
</impianto>
I've create with $xml = simplexml_load_string($xmlpost); in my POST.php this array :
SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => id1
)
[misure] => SimpleXMLElement Object
(
[misura] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[time] => 2016-01-01T01:01:01
[quantita] => 1234
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[time] => 2016-01-01T01:01:01
[quantita] => 3456
)
)
)
)
)
And i have to put ID, TIME , AND VALUE in to Database Table with foreach
Please Help ! Thank You !
Consider using SimpleXML's xpath() with a for loop on each node position of <misura>:
$xml = simplexml_load_string($xmlpost);
$count = count($xml->xpath('//misura'));
for($i = 1; $i <= $count; $i++){
$id = $xml->xpath('/impianto/#id')[0];
$qty = $xml->xpath('//misura['.$i.']/#time')[0];
$value = $xml->xpath('//misura['.$i.']/#quantita')[0];
echo $id.' '.$qty.' '.$value."\n"; // PASS VALUES INO MYSQL
}
# id1 1900-01-01T01:01:01+01:00 1
# id1 0001-01-01T00:00:00+01:00 -79228162514264337593543950335
# id1 9999-12-31T23:59:59.9999999+01:00 79228162514264337593543950335

PHP - how to search ID and display its value in a object

Hi I have an array of object like this
$json = json_decode($featureJson);
//which returns below
Array
(
[0] => stdClass Object
(
[productID] => 1
[productName] => Toyo
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
[1] => stdClass Object
(
[productID] => 2
[productName] => Maze
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
)
and I have another array that needs to match the ID of $json(Array of Objects) and return its productName.
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = '';
foreach ($IdArray as $item) {
$foo .= '{' . $item . '},';
}
echo $foo;
$foo return {1,2},{2,1} and I match $json so will display - {Toyo,Maze},{Maze,Toyo}, how can I do that? I have some hint using array_map()
but still got no idea to match in objects.
It's easier if you separate an array for the names first.
<?php
$featureJson = '[{"productID":1,"productName":"Toyo","assessments":[{"answer":"Yes"},{"answer":"No"}]},{"productID":2,"productName":"Maze","assessments":[{"answer":"Yes"},{"answer":"Yes"}]}]';
$json = json_decode($featureJson);
// Make an array of names
$names = [];
foreach($json as $products){
$names[$products->productID] = $products->productName;
};
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = [];
foreach ($IdArray as $ids) {
$ids = explode(',',$ids);
$fooItem = [];
foreach($ids as $id){
$fooItem[] = $names[$id];
}
$foo[]= '{' . implode(',',$fooItem) . '}'; }
echo implode(',',$foo);
Result:
{Toyo,Maze},{Maze,Toyo}
Check here

how to access array objects differently and dynamically

there is a xml document that i'm parsing to array..
how can i access those array objects and save them in new variables..?
this is piece of php code that is parsing
$contents = file_get_contents('test.xml');
$xml = simplexml_load_string($contents);
print_r($xml);
here is the xml that is being parsed
<?xml version='1.0'?>
<document>
<txtmsg>
<smstel>1234567</smstel>
<smstxt></smstxt>
<smsdir>Send</smsdir>
<smstime>06/01/2010 7:54:48 am</smstime>
</txtmsg>
<txtmsg>
<smstel>33333333</smstel>
<smstxt>Test sms hhTes12222222</smstxt>
<smsdir>Send</smsdir>
<smstime>06/01/2010 7:54:48 am</smstime>
</txtmsg>
<Contacts>
<conttime>06/01/2010 8:19:05 am</conttime>
<cnt>
<fn>Abc</fn>
<ln>Def</ln>
<cnttel>123456</cnttel>
<cntmtel>3333333</cntmtel>
<cntemail>abc#hotmail.com</cntemail>
</cnt>
<cnt>
<fn>def</fn>
<ln>ghi</ln>
<cnttel>234234</cnttel>
<cntmtel>2424</cntmtel>
<cntemail>df#hotmail.com</cntemail>
</cnt>
</Contacts>
</document>
and this is output.
SimpleXMLElement Object ( [txtmsg] => Array ( [0] => SimpleXMLElement Object ( [smstel] => 1234567 [smstxt] => SimpleXMLElement Object ( ) [smsdir] => Send [smstime] => 06/01/2010 7:54:48 am ) [1] => SimpleXMLElement Object ( [smstel] => 33333333 [smstxt] => Test sms hhTes12222222 [smsdir] => Send [smstime] => 06/01/2010 7:54:48 am ) ) [Contacts] => SimpleXMLElement Object ( [conttime] => 06/01/2010 8:19:05 am [cnt] => Array ( [0] => SimpleXMLElement Object ( [fn] => Abc [ln] => Def [cnttel] => 123456 [cntmtel] => 3333333 [cntemail] => abc#hotmail.com ) [1] => SimpleXMLElement Object ( [fn] => def [ln] => ghi [cnttel] => 234234 [cntmtel] => 2424 [cntemail] => df#hotmail.com ) ) ) )
how can i access each element of xml individually.. like smstel,smstxt,smsdir etc
Maybe I'm over simplifying it, but a loop.
foreach($xml->txtmsg as $txtmsg) {
echo $txtmsg->smstel;
echo $txtmsg->smstxt;
// more elements...
}
Note: When using XML it helps to be aware of the schema. Meaning the above example is specific to those elements you mentioned. Nonetheless, it should help you get started.
this is the best way you can do that..
foreach($xml->txtmsg as $txtmsg) {
echo $txtmsg->smstel;
// more elements...
}
Easy
(string)$xml->txtmsg->smstel
Same goes for params and lists.. its either an object property, or an array
echo $xml->txtmsg[0]->smstel; // 1234567
echo $xml->txtmsg[1]->smstel; // 3333333
$smsTel = (string) $xml->txtmsg[0]->smstel; // 1234567
To literally convert the <txtmsg> sections to a multidimensional array, you could do:
$array = array();
foreach ($xml->txtmsg as $msg) {
$array[] = array (
'smstel' => (string) $msg->smstel,
'smstxt' => (string) $msg->smstxt,
'smsdir' => (string) $msg->smsdir,
'smstime' => (string) $msg->smstime
);
}
print_r($array);
/*
Array
(
[0] => Array
(
[smstel] => 1234567
[smstxt] =>
[smstel] => Send
[smstime] => 06/01/2010 7:54:48 am
)
[1] => Array
(
[smstel] => 33333333
[smstxt] => Test sms hhTes12222222
[smstel] => Send
[smstime] => 06/01/2010 7:54:48 am
)
)
*/
here is the code.
it will be convert you SimpleXML Object to Array
function convertXmlObjToArr($obj, &$arr)
{
$children = $obj->children();
foreach ($children as $elementName => $node)
{
$nextIdx = count($arr);
$arr[$nextIdx] = array();
$arr[$nextIdx]['#name'] = strtolower((string)$elementName);
$arr[$nextIdx]['#attributes'] = array();
$attributes = $node->attributes();
foreach ($attributes as $attributeName => $attributeValue)
{
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
$arr[$nextIdx]['#attributes'][$attribName] = $attribVal;
}
$text = (string)$node;
$text = trim($text);
if (strlen($text) > 0)
{
$arr[$nextIdx]['#text'] = $text;
}
$arr[$nextIdx]['#children'] = array();
convertXmlObjToArr($node, $arr[$nextIdx]['#children']);
}
return;
}
you will get output in this format
Array
(
#name => books
#attributes => array ( )
#children => array
(
array
(
#name => novel
#attributes => array ( author => John Doe )
#children => array
(
array ( #name => title, #attributes => array ( ), #text => John's Novel )
)
)
)
)

Categories