I am trying to convert array to xml data in php. I am using xmlserializer pear package for this. My array is:
$arr=array(1000=>'name is john');
When I convert it to xml using this code:
options=array ('mode'=>'simplexml','addDecl'=>true,'indent'=>' ','rootName'=>'names');
$serializer = new XML_Serializer($options);
$result = $serializer->serialize($arr);
if($result == true)
$data=$serializer->getSerializedData();
echo $data;
I get following response:
<?xml version="1.0"?>
<names>name is john</names>
But I want this kind of response:
<?xml version="1.0"?>
<names>
<1000>name is john</1000>
</names>
can anyone tell where my mistake is?
I guess this is because numeric values are not allowed element names in XML. However, if you really want to have "xml-style" output like above (beside it is not real xml) you must bypass the library and code it by hand. I think this will do it for you:
public function xml_encode($array, $tag = "root"){
$result = '<'.$tag.'>';
foreach($array as $key => $value){
if(is_array($value)){
$result.=xml_encode($value, $key);
}else{
$result .= '<'.$key.'>'.$value.'</'.$key.'>';
}
}
$result .= '</'.$tag.'>';
return $result;
}
Related
I tried writing into my XML file with simpleXML and I wanted to write a string with the value "<test>asd</test>" then it turned into total giberrish (I know this is related with encoding formats but I don't know the solution to fix this, I tried turning into encoding="UTF-8" but it still yield a similar result)
My XML File:
<?xml version="1.0"?>
<userinfos>
<userinfo>
<account>
<user>TIGERBOY-PC</user>
<toDump>2014-02-04 22:17:22</toDump>
<nextToDump>2014-02-05 00:17:22</nextToDump>
<lastChecked>2014-02-04 16:17:22</lastChecked>
<isActive>0</isActive>
<upTime>2014-02-04 16:17:22</upTime>
<toDumpDone>1</toDumpDone>
<systemInfo><test>asd</test></systemInfo>
</account>
<account>
<user>TIGERBOY-PCV</user>
<toDump>2014-02-04 22:17:22</toDump>
<nextToDump>2014-02-05 00:17:22</nextToDump>
<lastChecked>2014-02-04 16:17:22</lastChecked>
<isActive>1</isActive>
<upTime>2014-02-04 16:17:22</upTime>
<toDumpDone>1</toDumpDone>
</account>
</userinfo>
</userinfos>
My PHP File:
<?php
//Start of Functions
function changeAgentInfo()
{
$userorig = $_POST['user'];
$userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file
$flag = false;
foreach ($userinfos->userinfo->account as $account)
{
// Checks if the user in this iteration of the loop is the same as $userorig (the user i want to find)
if($account->user == $userorig)
{
$flag = true; // Flag that user is found
$meow = "<test>asd</test>";
$account->addChild('systemInfo',$meow);
}
}
$userinfos->saveXML('userInfo.xml');
echo "Success";
}
//End of Functions
// Start of Program
changeAgentInfo();
?>
Thank you and have a nice day =)
This isn't gibberish; it is simply the XML entities for < (<) and > (>). To add nested XML elements with SimpleXML, you can do the following:
$node = $account->addChild('systemInfo');
$node->addChild('test', 'asd');
You'll see that first we add a node to <account>, then add a child to that newly created node.
If you plan on adding several children to the <systemInfo> element, you could perhaps do the following:
$items = array(
'os' => 'Windows 7',
'ram' => '8GB',
'browser' => 'Google Chrome'
);
$node = $account->addChild('systemInfo');
foreach ($items as $key => $value) {
$node->addChild($key, $value);
}
The addChild function is used to add the child element to an Xml node. You are trying to add xml instead of text.
You have
$meow = "<test>asd</test>";
$account->addChild('systemInfo',$meow);
You should change it to
$account->addChild('systemInfo','my system info text');
I've got an xml to parse with php, that contains some umlaut characters.
Every node that contains a string has the string wrapped in a cdata tag, but my problem starts before parsing the xml: when I load the file (I've also tried to print out the contents of the file with file_get_contests, same result), the umlaut characters get broken, so for example ü becomes ü. Running a htmlentities() is futile, as the characters are already broken at that point. The xml encode is utf-8, so I don't know what else to do to avoid this problem. Anyone can help me?
Edit:
xml sample 'locations.xml':
<?xml version="1.0" encoding="utf-8"?>
<locations>
<location>
<id>481</id>
<city><![CDATA[Zürich]]></city>
</location>
</locations>
php code:
function parseLocations(){
$xml = new DOMDocument();
$xml->load('locations.xml');
$xml->preserveWhiteSpace = false;
$data = array();
$locations = $xml->childNodes->item(0);
for($i=0; $i<$locations->childNodes->length; $i++){
$location = $locations->childNodes->item($i);
if($location->nodeName=="location"){
$tmp = parseVenue($location);
$data[] = $tmp;
}
}
echo var_export($data, true);
}
function parseVenue($location){
//I need to exclude some of the nodes
$exclude = array('#text');
$data = array();
for($i=0; $i<$location->childNodes->length; $i++){
$tag = $location->childNodes->item($i);
if(!in_array($tag->nodeName, $exclude)){
$data[$tag->nodeName] = $tag->nodeValue;
}
}
return $data;
}
echoed output:
array ( 0 => array ( 'id' => '481', 'city' => 'Zürich'), )
I'm taking my response from a Soap Request, and passing it into a new SimpleXML construct.
$response = $this->client->$method(array("Request" => $this->params));
$response_string = $this->client->__getLastResponse();
$this->response = new Classes_Result(new SimpleXMLElement($result));
If I echo the $response_string, it outputs a proper xml string. Here is a snippet as it's quite long.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><GetClassesResponse xmlns="http://clients.mindbodyonline.com/api/0_5">
<GetClassesResult>
<Status>Success</Status>
<XMLDetail>Full</XMLDetail>
<ResultCount>6</ResultCount>
<CurrentPageIndex>0</CurrentPageIndex>
<TotalPageCount>1</TotalPageCount>
<Classes>
<Class>
<ClassScheduleID>4</ClassScheduleID>
<Location>
<SiteID>20853</SiteID>
....</soap:Envelope>
Hoever, when I try to work with this object, I get errors or if I dump the object it outputs:
object(SimpleXMLElement)#51 (0)
Any ideas why this might be happening?
You are not actually using $response_string, and you have not set $result anywhere, which you have passed to new SimpleXMLElement($result).
Perhaps you intend to build a SimpleXML object with the $response_string string via simplexml_load_string()?
$response = $this->client->$method(array("Request" => $this->params));
$response_string = $this->client->__getLastResponse();
// Load XML via simplexml_load_string()
$this->response = new Classes_Result(simplexml_load_string($response_string));
// Or if you do expect a SimpleXMLElement(), pass in the string
$this->response = new Classes_Result(new SimpleXMLElement($response_string));
The <soap:Body> element of your SOAP response is namespaced with (soap). To loop over it with SimpleXML, you must provide the correct namespace:
// After creating new SimpleXMLElement()
var_dump($this->response->children("http://schemas.xmlsoap.org/soap/envelope/"));
// class SimpleXMLElement#2 (1) {
// public $Body =>
// class SimpleXMLElement#4 (0) {
// }
// }
To loop over the body:
foreach ($this->response->children("http://schemas.xmlsoap.org/soap/envelope/") as $b) {
$body_nodes = $b->children();
// Get somethign specific
foreach ($body_nodes->GetClassesResponse->GetClassesResult as $bn) {
echo $bn->ResultCount . ", ";
echo $bn->TotalPageCount;
}
}
// 6, 1
The xml is as follows:
<root>
<organizations>
<organization>
<info>
<orgID>1234</orgID>
<orgName>XYZ Company</orgName>
<address>
<address1>1 Main Street</address1>
<city>Somewhere</city>
<state>MI</state>
<zip>12334</zip>
</address>
</info>
</organization>
</organizations>
</root>
The code is as follows:
$ind = strpos($xmlResponse, "<");
$xml = simplexml_load_string(substr($xmlResponse, $ind));
//echo $xml;
$orgList = $xml->organizations->children();
foreach($orgList as $orgList)
{
echo $orgList->orgName;
}
And I get the following error:
Warning: main() [function.main]: Node no longer exists in...
The offending line is
foreach($orgList as $orgList)
Can anyone tell me what I'm doing wrong? I've tried accessing the xml through 50 different ways and either get that error or an empty xml object.
Thanks in advance!
It looks like you're overwriting the xml object when you loop with $orgList as $orgList. Try this instead:
foreach($orgList as $org)
echo $org->orgName;
Try the following:
$xml = simplexml_load_string($xml);
$org = $xml->organizations->children();
foreach($org as $k => $v)
{
echo $v->info->orgName;
}
Try using xpath
Put the XML in x.xml file
then create php file:
<?php
$xml = simplexml_load_file('x.xml');
$orgList = $xml->xpath("/root/organizations/organization/info");
print $orgList[0]->orgName;
?>
Hello i have this part of php code
$google_url = "http://uclassify.com/browse/uClassify/Sentiment/ClassifyText?readkey=jnsdnjdsnjnjsdnjsnjdsd&text=".$text."&version=1.01";
$result = file_get_contents($google_url);
$obj = simplexml_load_string($result);
$zaab = toArray($obj);
echo($zaab);
and the answer i get is
<?xml version="1.0" encoding="UTF-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01">
<status success="true" statusCode="2000"/>
<readCalls>
<classify id="cls1">
<classification textCoverage="0.6">
<class className="negative" p="0.999984"/> <-----p_value
<class className="positive" p="1.60692e-005"/> <-----p_value
</classification>
</classify>
</readCalls>
</uclassify>
how can i access p_values?
no after updating it gives me an error having to do with toArray()
You can get the all *p*s attribute values by looping through all *class*es like this:
$classes = $obj->readCalls->classify->classification->class;
foreach ($classes as $class) {
$p_val = $class->attributes()->p;
echo $p_val . "<br />";
}
I see you also tried to convert the xml string to array, probably the simplest way to do it is:
$json = json_encode($obj);
$xml_array = json_decode($json,TRUE);
To see the results use:
echo "<pre>";
print_r($xml_array);
echo "</pre>";
Use a xml parser.
http://php.net/manual/en/book.xml.php