How can i insert data from an XML into a database [duplicate] - php

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

Related

can't access values on parsing xml php [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 7 years ago.
I am trying to parse the xml response returned by url. I can successfully view the response but when I try to get the specific value from the xml, then I get nothing. Here is my PHP code.
$responseMessage = file_get_contents($myurl);
$xml = simplexml_load_string($responseMessage, 'SimpleXMLElement', LIBXML_NOCDATA);
print_r($xml)
Here's the actual xml response
<PPResponse Result="000" Key="99fd1c21-b07d-41f5-bbf8-1917f53c3152">
<ResultMessage>
Operation is succesfully completed
</ResultMessage>
<UtilityInfo>
<UtilityCode>78</UtilityCode>
</UtilityInfo>
<BillInfo>
<Bill>
<BillNumber>99fd1c21-b07d-41f5-bbf8-1917f53c3152</BillNumber>
<DueDate>2015-08-06T11:23:49</DueDate>
<Amount>0</Amount>
<ReserveInfo>Some info</ReserveInfo>
<BillParam>
<mask>3</mask>
<commission type="0" val="0.00" op="-" paysource="1" />
</BillParam>
<RefStan>7676422901773</RefStan>
</Bill>
</BillInfo>
</PPResponse>
Now I want to save only BillNumber value and RefStan Value into some variable so that I can use it later.
How can I do So?
You want to get attribute val from commission property? Try something like this:
$value = (string)$xml->BillInfo->Bill->BillParam->commission->attributes()->val;
Try
$str = <<<XML
<PPResponse Result="000" Key="99fd1c21-b07d-41f5-bbf8-1917f53c3152">
<ResultMessage>
Operation is succesfully completed
</ResultMessage>
<UtilityInfo>
<UtilityCode>78</UtilityCode>
</UtilityInfo>
<BillInfo>
<Bill>
<BillNumber>99fd1c21-b07d-41f5-bbf8-1917f53c3152</BillNumber>
<DueDate>2015-08-06T11:23:49</DueDate>
<Amount>0</Amount>
<ReserveInfo>Some info</ReserveInfo>
<BillParam>
<mask>3</mask>
<commission type="0" val="0.00" op="-" paysource="1" />
</BillParam>
<RefStan>7676422901773</RefStan>
</Bill>
</BillInfo>
</PPResponse>
XML;
$xml = new SimpleXMLElement($str);
echo $xml->ResultMessage;
echo $xml->BillInfo->Bill->ReserveInfo;
Note Please replace $str with $responseMessage.

find distinct values from two xml files using php [duplicate]

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

simpleXML creating a foreach [duplicate]

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

How to add attribute to xml header using SimpleXMLElement [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting SimpleXMLElement to include the encoding in output
PHP :
$xml = new SimpleXMLElement("<Title0></Title0>");
$xml->Title1='Some Text 1';
$output = $xml->asXML('mak.xml');
XML Output :
<?xml version="1.0"?>
<Title0>
<Title1>Some Text 1</Title1>
</Title0>
But I want to add attrbute like encoding="utf-8" to xml header , so that I can have something like this :
<?xml version="1.0" encoding="utf-8" ?>
<Title0>
<Title1>Some Text 1</Title1>
</Title0>
I dont want to use find and replace sort of things on the output file.
Read this:--
http://php.net/manual/en/simplexml.examples-basic.php
try this:-
Example #10 Adding elements and attributes
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');
echo $movies->asXML();
?>

XML values saved in a PHP array [duplicate]

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

Categories