This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
How to remove duplicate values from an array in PHP
(27 answers)
Closed 9 years ago.
i have some xml files as follows-
<?xml version="1.0"?>
<contacts>
<contact>
<mobile_no>9829344744</mobile_no>
<name>Sample Name 1</name>
<email>Some Email</email>
</contact>
<contact>
<mobile_no>9829344799</mobile_no>
<name>Sample Name 2</name>
<email>Some Email</email>
</contact>
<contact>
<mobile_no>9829345035</mobile_no>
<name>Sample Name 3</name>
<email>Some Email</email>
</contact>
</contacts>
i have two xml files in above format. each file has distinct <mobile_no>
but i want to extract distinct <mobile_no> from both files.
i have tried and use following code of php
$arr_filename[] = "file1.xml";
$arr_filename[] = "file2.xml";
$arr_contact = array();
foreach($arr_filename as $filename)
{
$xml = new simpleXMLElement($filename, null, true);
$contact_array1 = $xml->xpath('contact/mobile_no');
for($i=0; $i<count($contact_array1); $i++)
{
$arr_contact[$contact_array1[$i]]=true;
}
}
i found array $arr_contact with distinct contact no as its key
its working fine but problem is that when files has large content(records) and use more files (approximately 10) it takes too much time to process. i want to get more efficient method to extract distinct mobile no from more than one xml files. just as we extract distinct from more than one table in mysql.
Let's see, first merge:
$xml = simplexml_load_string($x1); // assume XML in $x1 and $x2
$xml2 = simplexml_load_string($x2);
// merge $xml2 into $xml
foreach ($xml2->contact as $contact) {
$newcontact = $xml->addChild("contact");
foreach ($contact->children() as $name => $value)
$newcontact->addChild($name, $value);
}
unset($xml2); // dispose $xml2
then select:
// use xpath to select <contact> with distinct contact/mobile_no
$results = $xml->xpath("/contacts/contact[not(mobile_no = following::mobile_no)]");
var_dump($results);
see it working: https://eval.in/86352
Related
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 3 years ago.
My asmx WEB service return this XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<PRODUCT>
<DESC>Vanilla ice cream</DESC>
<CODEERR>0</CODEERR>
</PRODUCT>
Calling WEB service from this PHP code
$SoapCli = new SoapClient('http://www.foo.com/MyService.asmx?WSDL');
$params = array(
'PARAM1' => 'some_param_1',
'PARAM2' => 'some_param_2',
);
$resp_WS = $SoapCli->__soapCall('MyFunction', array($params));
var_dump($resp_WS);
result is
object(stdClass)#11946 (1) {
["MyFunctionResult"]=>
object(stdClass)#11947 (1) {
["any"]=>
string(88) "<product xmlns=""><desc>Vanilla ice cream</desc><codeerr>0</codeerr></product>"
}
}
but, after googling a lot, I don't find PHP code for retreive values of two fields DESC and CODER
You can use json_encode,json_decode,simplexml_load_string to parse the XML response, try the following code snippet to read the XML response
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<PRODUCT>
<DESC>Vanilla ice cream</DESC>
<CODEERR>0</CODEERR>
</PRODUCT>';
$res = json_decode(json_encode((array)simplexml_load_string($xml)),true);
Now you can use $res['DESC'] and $res['CODEERR'] to retrive the values.
This question already has answers here:
How to convert XML attributes to text nodes
(3 answers)
Closed 7 years ago.
I want to write a PHP script that will modify my XML file.
I have my productId within the node as an attribute and I want to parse the entire file and convert it to a separate node. So I want to read the attribute of the node and put that attribute in its own node. But the rest of the nodes will stay as is.
Before:
<product id="123">
<name>bob</name>
<lastname>tim</lastname>
</product>
To:
<product>
<id>123</id>
<name>bob</name>
<lastname>tim</lastname>
</product>
Can I do this in PHP? Bearing in mind the file will have over one thousand separate products in it.
You could do it this way.
$xml = new SimpleXMLElement('<product id="123"></product>');
if(!empty($xml['id'])) {
$xml->addChild('id', $xml['id']);
unset($xml['id']);
}
echo $xml->asXML();
Output:
<?xml version="1.0"?>
<product><id>123</id></product>
Here's the manual's link and the addchild functions link. http://php.net/manual/en/class.simplexmlelement.php
http://php.net/manual/en/simplexmlelement.addchild.php
Update:
If you had multiple products you could loop like this.
$xml = new SimpleXMLElement('<proudcts><product id="123"></product><product id="234"></product></proudcts>');
foreach($xml as $key => $data){
if(!empty($data['id'])) {
$data->addChild('id', $data['id']);
unset($data['id']);
}
}
echo $xml->asXML();
Output:
<?xml version="1.0"?>
<proudcts><product><id>123</id></product><product><id>234</id></product></proudcts>
This question already has an answer here:
Import XML with content specified as attributes into a MySQL table?
(1 answer)
Closed 7 years ago.
I want to insert the following XML file into a Mysql database using php
<?xml version="1.0" encoding="UTF-8"?>
<PrintLetterBarcodeData
uid="725733706873"
name="RAVINDER KUMAR"
gender="M"
yob="1996"
co="S/O KAKA RAM"
house="460A"
street="WARD NO. 6"
lm="NA"
loc="NA"
vtc="Nanyola (292)"
po="Naneola"
dist="Ambala"
state="Haryana"
pc="134003"
/>
How do I extract the data from this XML file to insert them into a database ?
For the PHP approach, you will find the following useful:
<?php
$string = <<<XML
<PrintLetterBarcodeData
uid="725733706873"
name="RAVINDER KUMAR"
gender="M"
yob="1996"
co="S/O KAKA RAM"
house="460A"
street="WARD NO. 6"
lm="NA"
loc="NA"
vtc="Nanyola (292)"
po="Naneola"
dist="Ambala"
state="Haryana"
pc="134003"
/>
XML;
$xml = simplexml_load_string($string);
$attribs = $xml->attributes();
// convert the '$attribs' to an array
foreach($attribs as $key=>$val) {
$arrayOfAttribs[(string)$key] = "'".(string)$val."'";
}
$namesOfColumns = implode(",", array_keys($arrayOfAttribs));
$valuesOfColumns = implode(",", array_values($arrayOfAttribs));
// your database stuff
$query = "INSERT INTO yourtable ($namesOfColumns) VALUES ($valuesOfColumns);";
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
foreach and simplexml
I have got my XML document loading correct but I am unsure how I can create a simple foreach were I can have [PictureHref] [Title] and [PriceDisplay] loaded for each item given in the feed.
I cannot find a clear example in the documentation.
XML Example
Currently my PHP code consists of the following:
$mainUrl = 'http://api.trademe.co.nz/v1/Member/{id}/Listings/All.xml';
$xmlFeed = simplexml_load_file($mainUrl);
XML
<Listings xmlns="http://api.trademe.co.nz/v1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TotalCount>1</TotalCount>
<Page>1</Page>
<PageSize>1</PageSize>
<List>
<Listing>
<ListingId>527496168</ListingId>
<Title>Clifftop Resort style Living with stunning aspect</Title>
<Category>0350-5748-3399-</Category>
<StartPrice>0</StartPrice>
<StartDate>2012-10-26T21:24:47.073Z</StartDate>
<EndDate>2012-12-21T21:24:47.073Z</EndDate>
<ListingLength i:nil="true" />
<HasGallery>true</HasGallery>
<AsAt>2012-10-28T22:48:47.409946Z</AsAt>
<CategoryPath>/Trade-me-property/Residential/For-sale</CategoryPath>
<PictureHref>http://images.trademe.co.nz/photoserver/thumb/10/239043710.jpg</PictureHref>
<RegionId>2</RegionId>
<Region>Auckland</Region>
<Suburb>North Shore</Suburb>
<NoteDate>1970-01-01T00:00:00Z</NoteDate>
<ReserveState>NotApplicable</ReserveState>
<IsClassified>true</IsClassified>
<GeographicLocation>
<Latitude>-36.5681333</Latitude>
<Longitude>174.6936265</Longitude>
<Northing>5951700</Northing>
<Easting>1751547</Easting>
<Accuracy>Address</Accuracy>
</GeographicLocation>
<PriceDisplay>To be auctioned</PriceDisplay>
</Listing>
</List>
</Listings>
All you need is
$url = simplexml_load_file("__YOUR__URL___");
$listing = $url->List->Listing;
echo "<pre>";
echo $listing->PictureHref, PHP_EOL;
echo $listing->Title, PHP_EOL;
echo $listing->PriceDisplay, PHP_EOL;
While I'd recommend the use of DOMDocument instead of SimpleXML, here's how you'd do that in SimpleXML:
$data = array();
foreach($xmlFeed->List as $item) {
$data[] = array(
(string) $item->Listing->PictureHref,
(string) $item->Listing->Title,
(string) $item->Listing->PriceDisplay
);
}
You can see it (sorta, I had to change some things) at CodePad
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP - How to parse this xml?
Parse xml with php - storing parts into array (close to deletion or already deleted)
If I had the following XML file and I wanted to save the values in the tags name and number into an array called department, how would I be able to do it using PHP?
<?xml version="1.0"?>
<data>
<record id="1">
<department>
<name>ACME</name>
<number>5</number>
</department>
<floor>
<name>ACME Floor</name>
<number>5</number>
</floor>
</record>
</data>
You should use
DOMDocument::loadXML
<?php
$doc = new DOMDocument();
$doc->load('book.xml');
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
echo $book->nodeValue, PHP_EOL;
}
?>