Parsing XML with php to Array - php

I've tried to parse a XML String with php.
The example of XML is
<?xml version="1.0"?>
<root>
<Log>
<Item>
<name>![CDATA[James]]</name>
<address>![CDATA[Korea]]</address>
<email>![CDATA[Korea#gmail.com]]</email>
</Item>
<Item>
<name>![CDATA[James2]]</name>
<address>![CDATA[Korea2]]</address>
<email>![CDATA[Korea#gmail.com2]]</email>
</Item>
</Log>
</root>
My Parsing PHP Code is
$xml = simplexml_load_string($input,null,LIBXML_NOCDATA);
$xml=json_decode( json_encode( $xml),true);
However, When I try to get sizeof($xml['Log']['Item']), have some problems.
If XML have One 'Item' , then sizeof($xml['Log']['Item']) return '3' .
but If XML have 4 'Item's , then it return '4'.
I want to return 1, if XML have One 'Item'.
How can I solve this problem.?

I solved this parsing problem with foreach().
$xml = simplexml_load_string($input,null,LIBXML_NOCDATA);
$itemArray=$xml->Log->Item;
$i=0;
$sqlParamArray= array();
foreach ($itemArray as $tag) {
$name= trim($tag->name);
$address= trim($tag->address);
$email= trim($tag->email);
array_push($sqlParamArray,$name,$address,$email);
$i++;
}
echo $i;
....
sizeof('Item') is saved in $i.
I solved it.

Related

read Soap Response XML and insert into mysql

i'm trying to read response from XML SOAP file and then i need to insert it into the database
here's the XML Code
<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<MobileAgentAPI:invokeResponse>
<invokeReturn>
<values xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="MobileAgentAPI:SoapMapValue[4]">
<item>
<name>balance</name>
<singleValue>330123</singleValue>
</item>
<item>
<name>returnCode</name>
<singleValue>00</singleValue>
</item>
<item>
<name>transactionStatus</name>
<singleValue>00</singleValue>
</item>
<item>
<name>errorCode</name>
<singleValue>0</singleValue>
</item>
</values>
</invokeReturn>
</MobileAgentAPI:invokeResponse>
</SOAP-ENV:Body>
the question is.
how do i read the response and then insert the data into mysql?
thanks in advance
------UPDATE-------------------
I've tried this approach
$combi = '<XML Response>';
$doc = new DOMDocument();
$doc->loadXML($combi);
echo $doc->getElementsByTagName('name')->item(0)->nodeValue;
and it returns
balance
how do i loop through every node?
and print it like
balance : 330123
returnCode : 00
errorCode : 0
and then insert it into mysql
You can load the XML via DOMDocument in PHP and go through every node
more at: http://php.net/manual/de/class.domdocument.php
if you can specify your question i could help you more
update:
$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
echo $book->nodeValue, PHP_EOL;
}
instead of echo you could implement your sql code for each node
update 2:
$doc->loadXML($combi);
$data = $doc->getElementsByTagName('item');
foreach($data as $data){
echo $data->item(0)->nodeValue . " : " . $data->item(1)->nodeValue, PHP_EOL;
}

Parse XML with PHP

This is what my XML looks like
<?xml version="1.0" encoding="UTF-8"?>
<item>
<date>May 2013</date>
<html>http://www.link.to/html.html</html>
</item>
I do this in the PHP and it kind of works
$file = '../modules/xml/nl-archive.xml';
$xml = simplexml_load_file($file);
$string = '';
foreach($xml as $item){
$string .= '<a href="'.$item->html .'" ><li>'.$item->date .'</li></a>';
}
Just trying to get the contents of the date tag and html tag to show up for each of the item tags. Been googling and tinkering, can't get it right. What am I doing wrong?
Try changing your XML to have a root with children like:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<date>May 2013</date>
<html>http://www.link.to/html.html</html>
</item>
</items>
Php is just fine as you have it.

Getting a specific part from XML

I am trying to get the PAY where it has the ID 3 Where it says the label phone
but i really dont know how, i tried everything.
Thanks for helping!
Here is the XML code:
$books = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
<login>1</login>
<arrStatsData>
<item>
<Id>500</Id>
<Label>website_name</Label>
<Data>
<item>
<Id>4</Id>
<Label>transactions</Label>
<Data>
<sum>2029.34</sum>
<cst>47.67575</cst>
<num>86</num>
<avg>23.6</avg>
<pay>1981.66</pay>
</Data>
</item>
<item>
<Id>3</Id>
<Label>Phone</Label>
<Data>
<sum>205</sum>
<cst>17.353</cst>
<num>205</num>
<avg>1</avg>
<pay>187.647</pay>
</Data>
</item>
......
PHP Code:
$xml = simplexml_load_string($arrResult); //load xml from above
foreach($xml->arrStatsData->item->Data as $item)
{
foreach($item->item as $DATA)
{
echo $DATA->Id.'<br>';
}
My result now is:
1981.66
187.647
-0.4448
Since you know some information that's tell the node apart from the rest you can use XPath to get the value directly instead of iterating through all of them:
<?php
$sxe = new SimpleXMLElement($books);
$pay = $sxe->xpath('//item[./Id=3]/Data/pay');
echo (string) $pay[0];
Ouput:
187.647
Your PHP code would be like this:
$xml = simplexml_load_string($books);
foreach($xml->arrStatsData->item->Data as $item)
{
//echo '$item;';
foreach($item->item as $DATA)
{
if($DATA->Id == '3'){
echo $DATA->Data->pay."<br/>";
}
}
}
It retrieve the pay value when the ID is equals to 3.
Rolando Isidoro was faster to recommend xpath, my solution is slightly different, that's why I post it, too:
$pay = (string)$xml->xpath("//item[Id = '3']/Data/pay")[0];
echo $pay;
see it working: http://codepad.viper-7.com/qzPlmp

Parse XML in PHP by specific attribute

I need to get <name> and <URL> tag's value where subtype="mytype".How can do it in PHP?
I want document name and test.pdf path in my result.
<?xml version="1.0" encoding="UTF-8"?>
<test>
<required>
<item type="binary">
<name>The name</name>
<url visibility="restricted">c:/temp/test/widget.exe</url>
</item>
<item type="document" subtype="mytype">
<name>document name</name>
<url visiblity="visible">c:/temp/test.pdf</url>
</item>
</required>
</test>
Use SimpleXML and XPath, eg
$xml = simplexml_load_file('path/to/file.xml');
$items = $xml->xpath('//item[#subtype="mytype"]');
foreach ($items as $item) {
$name = (string) $item->name;
$url = (string) $item->url;
}
PHP 5.1.2+ has an extension called SimpleXML enabled by default. It's very useful for parsing well-formed XML like your example above.
First, create a SimpleXMLElement instance, passing the XML to its constructor. SimpleXML will parse the XML for you. (This is where I feel the elegance of SimpleXML lies - SimpleXMLElement is the entire library's sole class.)
$xml = new SimpleXMLElement($yourXml);
Now, you can easily traverse the XML as if it were any PHP object. Attributes are accessible as array values. Since you're looking for tags with specific attribute values, we can write a simple loop to go through the XML:
<?php
$yourXml = <<<END
<?xml version="1.0" encoding="UTF-8"?>
<test>
<required>
<item type="binary">
<name>The name</name>
<url visibility="restricted">c:/temp/test/widget.exe</url>
</item>
<item type="document" subtype="mytype">
<name>document name</name>
<url visiblity="visible">c:/temp/test.pdf</url>
</item>
</required>
</test>
END;
// Create the SimpleXMLElement
$xml = new SimpleXMLElement($yourXml);
// Store an array of results, matching names to URLs.
$results = array();
// Loop through all of the tests
foreach ($xml->required[0]->item as $item) {
if ( ! isset($item['subtype']) || $item['subtype'] != 'mytype') {
// Skip this one.
continue;
}
// Cast, because all of the stuff in the SimpleXMLElement is a SimpleXMLElement.
$results[(string)$item->name] = (string)$item->url;
}
print_r($results);
Tested to be correct in codepad.
Hope this helps!
You can use the XML Parser or SimpleXML.

PHP: passing an xml node to function

i'm trying to pass an xml node to a function but can't figure out how - here's my xml markup:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
<form>
<item>
<id>frm1</id>
<dbID>1</dbID>
<visible>1</visible>
</item>
</form>
<form>
<item>
<id>frm2</id>
<dbID>2</dbID>
<visible>1</visible>
</item>
</form>
</root>
when setting up a foreach loop - how's the syntax to iterate through the xml and passing the whole node to a function?
i've tried something like:
foreach($xml as $ctlXML => $value)
{
$ctl = generateCTL($ctlXML);
}
but it doesn't work as it should.
thanks
If you are using SimpleXML it is simple as
$xml = simplexml_load_file($path_to_file);
foreach($xml->form as $form){
$ctl = generateCTL($form->item);
}
Be careful - $form->item is an object

Categories