PHP and XML answer from server - php

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

Related

PHP Search between two points

I'm trying to deal with some XML in PHP.
I have code, such as this:
<?php
$stream = fopen("xml","r");
?>
Where "xml" contains something such as this:
<name>name1</name>
<key>key1</key>
<name>name2</name>
<key>key2</key>
etc.
I'd like to create an array out of the contents of the <key> tags, something like where
keys[0] = "key1"
and
keys[1] = "key2"
Any help is appreciated, thank you very much :)
Solution:
$xmlstr = fread($stream,filesize("xml-file"));
$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->getName() . "\n";
foreach ($sxe->children() as $child) {
echo $child->children();
}
You should use DOM functions for this case. Let's suppose a well-formed XML document (xmltest.xml):
<?xml version="1.0" encoding="utf-8"?>
<root>
<name>name1</name>
<key>key1</key>
<name>name2</name>
<key>key2</key>
</root>
This code loads the xml file into DOM document and gets all nodes with tag key;
<?php
$dom = new DOMDocument('1.0','utf-8');
$dom->load('xmltest.xml');
$keys = $dom->getElementsByTagName('key');
for ($i = 0; $i < $keys->length; $i++) {
echo $keys->item($i)->nodeValue . "</br>";
}
?>

Displaying XML feed contents

Using simpleXML, how do you display the contents of a feed. I mean actually display the XML on a page so that I can see the schema?
In my example i will use XML file like:
<?xml version="1.0" encoding="UTF-8"?>
<module>
<name>Menus</name>
<folder>menus</folder>
<install>install.php</install>
</module>
You can use to load xml file in a variable:
$mod = simplexml_load_file($XMLfile);
and call fields:
echo $mod->module->name;
echo $mod->module->folder;
echo $mod->module->install;
Hope this helps.
$xml = simplexml_load_file("URL GOES HERE");
echo "<pre>";
print_r($xml);
echo "</pre>";
Will print a readable array of the object.
And a VALID RSS feed has this schema:
foreach($xml->channel->item as $items){
$title = $items->title;
$link = $items->link;
$description = $items->description;
$pubDate = strtotime($items->pubDate);
$pubDate = date('Y-m-d H:i:s', $pubDate);
}
Along with a few other attributes.

Empty xml object when using SimpleXML - Node no longer exists

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;
?>

Numeric Values in xml tag

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;
}

xml parsing with php

I would like to create a new simplified xml based on an existing one:
(using "simpleXml")
<?xml version="1.0" encoding="UTF-8"?>
<xls:XLS>
<xls:RouteInstructionsList>
<xls:RouteInstruction>
<xls:Instruction>Start</xls:Instruction>
</xls:RouteInstruction>
</xls:RouteInstructionsList>
<xls:RouteInstructionsList>
<xls:RouteInstruction>
<xls:Instruction>End</xls:Instruction>
</xls:RouteInstruction>
</xls:RouteInstructionsList>
</xls:XLS>
Because there are always colons in the element-tags, it will mess with "simpleXml", I tried to use the following solution->link.
How can I create a new xml with this structure:
<main>
<instruction>Start</instruction>
<instruction>End</instruction>
</main>
the "instruction-element" gets its content from the former "xls:Instruction-element".
Here is the updated code:
But unfortunately it never loops through:
$source = "route.xml";
$xmlstr = file_get_contents($source);
$xml = #simplexml_load_string($xmlstr);
$new_xml = simplexml_load_string('<main/>');
foreach($xml->children() as $child){
print_r("xml_has_childs");
$new_xml->addChild('instruction', $child->RouteInstruction->Instruction);
}
echo $new_xml->asXML();
there is no error-message, if I leave the "#"…
/* the use of # is to suppress warning */
$xml = #simplexml_load_string($YOUR_RSS_XML);
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->children() as $child)
{
$new_xml->addChild('instruction', $child->RouteInstruction->Instruction);
}
/* to print */
echo $new_xml->asXML();
You could use xpath to simplify things. Without knowing the full details, I don't know if it will work in all cases:
$source = "route.xml";
$xmlstr = file_get_contents($source);
$xml = #simplexml_load_string($xmlstr);
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->xpath('//Instruction') as $instr) {
$new_xml->addChild('instruction', (string) $instr);
}
echo $new_xml->asXML();
Output:
<?xml version="1.0"?>
<main><instruction>Start</instruction><instruction>End</instruction></main>
Edit: The file at http://www.gps.alaingroeneweg.com/route.xml is not the same as the XML you have in your question. You need to use a namespace like:
$xml = #simplexml_load_string(file_get_contents('http://www.gps.alaingroeneweg.com/route.xml'));
$xml->registerXPathNamespace('xls', 'http://www.opengis.net/xls'); // probably not needed
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->xpath('//xls:Instruction') as $instr) {
$new_xml->addChild('instruction', (string) $instr);
}
echo $new_xml->asXML();
Output:
<?xml version="1.0"?>
<main><instruction>Start (Southeast) auf Sihlquai</instruction><instruction>Fahre rechts</instruction><instruction>Fahre halb links - Ziel erreicht!</instruction></main>

Categories