How can I extract value from an xml - php

I'm new to PHP. I'm trying to get the data out of the below XML. Now, in my code $data->Address contains value of the below code i.e:
$data->Address = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
Now I want to extract the <contactpersonname> tag and print it. How can I do this?

Since your XML is missing a tag that encompasses all others, you need to create on in order to get parsers to work properly:
<?php
$buffer = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
// ***** wrap the whole thing in a <root> tag...
$xml = simplexml_load_string("<root>".$buffer."</root>");
$array = json_decode(json_encode((array) $xml), 1);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
Result:
Array
(
[tolist] => Array
(
)
[cclist] => Array
(
[cc] => Array
(
[0] => Array
(
[contactpersonname] => niraj
[name] => niraj
[email] => stgh#gmail.com
[number] => +91.3212365212
[prefix] => Ms.
[contactpersonprefix] => Ms.
)
[1] => Array
(
[contactpersonname] => fdg
[name] => admin
[email] => admin12#gmail.com
[number] => +91.4554343234
[prefix] => Mr.
[contactpersonprefix] => Mr.
)
)
)
)
UPDATED
Now you can navigate down to where you want to go with
echo "<pre>";
$ccList = $array['cclist'];
$cc = $ccList['cc'];
$contacts = array();
foreach($cc as $i=>$val) {
$contacts[$i]=$val['contactpersonname'];
}
echo "first contact: " . $contacts[0] . "<br>";
echo "second contact: " . $contacts[1] ."<br>";
Result:
first contact: niraj
second contact: fdg

You can convert the XML to an array with the following code:
$xml = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), 1);
Where $buffer is the xml string.
Then you can obtain the person name as follow:
$data->Address = $array['cclist']['cc']['contactpersonname'];
It's a quick and dirty method to convert the xml to an array, but it works.

Try this..
$xml = new SimpleXMLElement($string);
$results = $xml->xpath('cclist/cc/contactpersonname');
http://php.net/manual/en/simplexmlelement.xpath.php

$xml = simplexml_load_file("note.xml");
echo $xml->contactpersonname;
This requires you to load it form an xml file. If you already have the string in the code I'd recommend a regex. If you know the data won't ever be incorrect written!
$pattern = '#<contactpersonname>(.*?)</contactpersonname>#';
echo preg_match ($pattern, $data->Address);

Related

How can i get json in php

I get an array from json but i don't know how to get bookTitle and url.
How can i read this items in the arrays ?
$data = file_get_contents('C:\Users\rsanchro\Desktop\ftp brasil4-9-2015\moderna_plus-historia\MPCH-C05-P1-1.0.1-ZIP-PT\resource.json');
$datos = json_decode($data, true);
print_r($datos);die;
Results:
Array
(
[topBarColor] => #000000
[bookId] => 2aef55bf3a9dec377b4f16a8048c7f84
[bookTitle] => História
[unitId] => MPCH-C05-P1
[unitTitle] => 108-127-MPCH-C05-P1-M
[unitResources] => Array
(
[0] => Array
(
[type] => 03
[url] => resources/mphis_c06av_escultura_ontem.mp4
[urlToShowInsideUnit] => #/compId/id0a33b2a0471e0f444bc0a88b5bb55714
[title] => A escultura ontem e hoje
[page] => 123
)
)
)
Use this
print_r(utf8_decode($datos['bookTitle']));
if(is_array($datos['unitResources']) && count($datos['unitResources']) > 0){
foreach($datos['unitResources'] as $key => $value){
print_r($value['url']);
}
}
if you are having only single data use the following
$bookTitle=$datos['bookTitle'];
$url=$datos['unitResources'][0]['url'];
If you have more than one data in the array then use the following
foreach($datos as $dato){
$bookTitle=$dato['bookTitle'];
$urls=array();
foreach($datos['unitResources'] as $url){
$urls[]=$url['url'];
}
echo '<br>Book Title :'.$bookTitle;
echo '<br>urls :';
foreach($urls as $url){
echo $url.'<br>';
}
}
For your example array which you mentioned. you can use the first method.
but since you are working with array better use the 2nd method.
Try this
echo "Title:".$datos['bookTitle']; //To print book title
//To print url
if(is_array($datos['unitResources']) && count($datos['unitResources']) > 0){
foreach($datos['unitResources'] as $key => $value){
echo "URL:".$value['url'] ;
}
}
I'd also recommend taking a look at the jsonselect library. It provides an intuitive selection syntax that is modeled after CSS selector syntax.
JSON Select project site:
http://jsonselect.org/#overview
PHP implementation:
https://github.com/observu/JSONselect-php

Storing XML Document with XPath and PHP, tag info isn't storing in array like needed

So, I want to iterate through the XML by the attributes of and then print the tags from within the coordinating tag. This is the structure:
<emp salesid="1">
<report>07-14-2015_DPLOH_SalesID_1.pdf</report>
<report>07-17-2015_DPLOH_SalesID_1.pdf</report>
<report>07-14-2015_DTE_SalesID_1.pdf</report>
<report>07-14-2015_IDT_SalesID_1.pdf</report>
<report>07-14-2015_Kratos_SalesID_1.pdf</report>
<report>07-14-2015_Spark_SalesID_1.pdf</report>
</emp>
Here is the my code:
$xml = new SimpleXMLElement($xmlStr);
foreach($xml->xpath("//emp/report") as $node) {
//For all found nodes retrieve its ID from parent <emp> and store in $arr
$id = $node->xpath("../#salesid");
$id = (int)$id[0];
if(!isset($arr[$id])) {
$arr[$id] = array();
}
//Then we iterate through all nodes and store <report> in $arr
foreach($node as $report) {
$arr[$id][] = (string)$report;
}
}
echo "<pre>";
print_r($arr);
echo "</pre>";
However, this is what I get for output:
Array
(
[1] => Array
(
)
[10] => Array
(
)
... and it continues to iterate through all of the attributes of tags, but never fills the array with any information.
If anyone could help tell me what I'm missing, I would GREATLY appreciate it. I feel like I'm losing my mind over what seems like should be rather simple.
Thanks!
You're very close. The code isn't working because of the second for loop. The outer loop will iterate through all of the report elements. So, node is a report element. When you try to iterate through the children of report, there's nothing there.
Instead of the second (inner) loop, simply do this:
$arr[$id][] = (string)$node;
When I did, I got the following result:
<pre>
Array
(
[1] => Array
(
[0] => 07-14-2015_DPLOH_SalesID_1.pdf
[1] => 07-17-2015_DPLOH_SalesID_1.pdf
[2] => 07-14-2015_DTE_SalesID_1.pdf
[3] => 07-14-2015_IDT_SalesID_1.pdf
[4] => 07-14-2015_Kratos_SalesID_1.pdf
[5] => 07-14-2015_Spark_SalesID_1.pdf
)
)
I updated your script to work slightly differently:
$emp = new SimpleXMLElement($xmlStr);
$id = intval($emp['salesid']);
$arr = array(
$id => array(),
);
$lst = $emp->xpath('/emp/report');
while (list(, $text) = each($lst))
{
$arr[$id][] = (string) $text;
}
echo "<pre>";
print_r($arr);
echo "</pre>";
Cheers

getting attributes in simplexml_load_string

Below is the function which i am using to convert xml to array
$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
$array = json_decode(json_encode($obj), true); // Convert to array
when i try with the parent node "xml"
<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>
i get this result
Array
(
[CodeshareInfo] => ETIHAD AIRWAYS
)
but if i try without parent node "xml"
<CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo>
i can get the attributes and the value
Array
(
[#attributes] => Array
(
[OperatingCarrier] => EY
[OperatingFlightNumber] => 269
)
[0] => ETIHAD AIRWAYS
)
what should i change in code to get the output with attributes and values as my xml data is from a soap request and once i receive i will convert as array to access its value and attributes.
Given the provided XML you can iterate through it and pull out the attributes and values.
<?php
$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
foreach($obj as $ob) {
echo $ob['OperatingCarrier'] . "\n";
echo $ob . "\n";
echo $ob['OperatingFlightNumber'] . "\n";
}
Output:
EY
ETIHAD AIRWAYS
269

Achieving same array structure when converting from JSON and XML

I'm trying to build my first public API, which is going pretty fine, but i ran into some trouble converting different data formats that will get POSTed. Basically, the API should accept both JSON and XML, and now i'm trying to convert those into a common PHP array structure.
For JSON my example looks like this:
$people = array( array('name' => 'casper',
'shoesize' => 41
),
array('name' => 'christine',
'shoesize' => 37
)
);
$data = json_encode($people);
return json_decode($data);
This will result in:
[{"name":"casper","shoesize":"41"},{"name":"charlotte","activated":"1"}]
The XML example is as follows:
$xml = '<?xml version="1.0"?>'.
'<people>'.
'<person>'.
'<name>casper</name>'.
'<shoesize>41</shoesize>'.
'</person>'.
'<person>'.
'<name>christine</name>'.
'<shoesize>37</name>'.
'</person>'.
'</people>';
$xml = simplexml_load_string($xml);
$data = json_encode($xml);
return json_decode($data);
This will result in:
{"person":[{"name":"casper","shoesize":"42"},{"name":"christina","shoesize":"12"}]}
Can anyone figure out how i will be able to achieve the same array structure in both examples?
i think this could help you :-
$xml = '<?xml version="1.0"?>'.
'<people>'.
'<person>'.
'<name>casper</name>'.
'<shoesize>41</shoesize>'.
'</person>'.
'<person>'.
'<name>christine</name>'.
'<shoesize>37</shoesize>'.
'</person>'.
'</people>';
$xml = simplexml_load_string($xml);
$data = json_encode($xml);
echo '<pre>';
$dataarray=(json_decode($data,true));
$requiredarray=$dataarray['person'];
print_r($requiredarray);
Output :-
Array
(
[0] => Array
(
[name] => casper
[shoesize] => 41
)
[1] => Array
(
[name] => christine
[shoesize] => 37
)
)

How to make variable that's in an array format into an array

This is probably a simple question, but how do I take a variable like the following and make it into an array.
$hot = "It","is","hot","outside";
Doing the following doesn't work:
$newhot = array($hot);
I'm actually calling an API that looks like:
[["P0010001","NAME","state","zip code tabulation area"],
["68191","ZCTA5 99301","53","99301"]]
What I need is the population on the second line (first quotes).
Doing the following gives me "68191","ZCTA5 99301","53","99301"
$splitContent = implode("\n",array_slice(explode("\n",$populate),1,2));
$newContent = str_replace(']','',$splitContent);
$newContent = str_replace('[','',$newContent);
This
$hot = "It","is","hot","outside";
will generate error in PHP. But let's say you have the following retrieved from the API:
$str='[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]';
then, if you run this line:
$myArray = json_decode($str);
and then
echo "<pre>";
print_r($myArray);
echo"</pre>";
you can have this result:
Array
(
[0] => Array
(
[0] => P0010001
[1] => NAME
[2] => state
[3] => zip code tabulation area
)
[1] => Array
(
[0] => 68191
[1] => ZCTA5 99301
[2] => 53
[3] => 99301
)
)
Second line of data will be stored in
$myArray[1]
Defining an array is something like...
$hot = array("It","is","hot","outside");
Re: Your Api call...
$ApiResponse = '[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]';
$Response = json_decode($ApiResponse);
$Data = $Response[1];
Specifically, the api is returning a list of lists. We're taking the 2nd (0-indexed) list. $Data will now be the same as if you'd declared...
$Data = array("68191","ZCTA5 99301","53","99301");
Edit: Tested Code...
$Key = '[Your Key]';
$ApiResponse = file_get_contents("http://api.census.gov/data/2010/sf1?key={$Key}&get=P0010001,NAME&for=zip+code+tabulation+area:99301&in=state:53");
print "Raw: " . print_r($ApiResponse, true) . "<hr/>";
$Response = json_decode($ApiResponse);
$Data = $Response[1];
print "Extracted Data: " . print_r($Data, true) . "<br/>";
print "First bit of data: {$Data[0]}.<br/>";
print "Second bit of data: {$Data[1]}.<br/>";

Categories