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;
}
?>
Related
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:
Create XML with xmlns:xlink attribute in a node
(1 answer)
Closed 8 years ago.
Thanks for your help, I need php script to generate the following XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<design xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://anydomain.com">
<name>xxx</name>
<description>yyy</description>
</design>
You could use SimpleXML to create such xml.
Rough example:
$xml = new SimpleXMLElement('<design />'); // set parent node
$xml->addAttribute('xmlns', 'http://anydomain.com'); // attributes
$xml->addAttribute('xlink:ns', '', 'http://www.w3.org/1999/xlink');
unset($xml->attributes('xlink', true)['ns']);
$xml->addChild('name', 'xxx'); // add those children
$xml->addChild('description', 'yyy');
echo $xml->asXML(); // output
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
This question already has an answer here:
php simple xml parse problem on invalid tags
(1 answer)
Closed 9 years ago.
I want to parse an XML data stored in a variable, using Simple XML.
THis is the data I am talking about:
<SearchResults:searchresults xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd /vstatic/ae1bf8a790b67ef2e902d2bc04046f02/static/xsd/SearchResults.xsd">
<request>
<address>2114 Bigelow Ave</address>
<citystatezip>Seattle, WA</citystatezip>
</request>
<message>
<text>Request successfully processed</text>
<code>0</code>
</message>
<response>
<results>
<result>
<zpid>48749425</zpid>
<links>
<homedetails>http://www.zillow.com/homedetails/2114-Bigelow-Ave-N-Seattle-WA-98109/48749425_zpid/</homedetails>
<graphsanddata>http://www.zillow.com/homedetails/charts/48749425_zpid,1year_chartDuration/?cbt=7522682882544325802%7E9%7EY2EzX18jtvYTCel5PgJtPY1pmDDLxGDZXzsfRy49lJvCnZ4bh7Fi9w**</graphsanddata>
<mapthishome>http://www.zillow.com/homes/map/48749425_zpid/</mapthishome>
<comparables>http://www.zillow.com/homes/comps/48749425_zpid/</comparables>
</links>
<address>
<street>2114 Bigelow Ave N</street>
<zipcode>98109</zipcode>
<city>Seattle</city>
<state>WA</state>
<latitude>47.63793</latitude>
<longitude>-122.347936</longitude>
</address>
<zestimate>
<amount currency="USD">1219500</amount>
<last-updated>11/03/2009</last-updated>
<oneWeekChange deprecated="true"/>
<valueChange duration="30" currency="USD">-41500</valueChange>
<valuationRange>
<low currency="USD">1024380</low>
<high currency="USD">1378035</high>
</valuationRange>
<percentile>0</percentile>
</zestimate>
<localRealEstate>
<region id="271856" type="neighborhood" name="East Queen Anne">
<zindexValue>525,397</zindexValue>
<zindexOneYearChange>-0.144</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/East-Queen-Anne/r_271856/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/East-Queen-Anne-Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/east-queen-anne-seattle-wa/</forSale>
</links>
</region>
<region id="16037" type="city" name="Seattle">
<zindexValue>381,764</zindexValue>
<zindexOneYearChange>-0.074</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/r_16037/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/seattle-wa/</forSale>
</links>
</region>
<region id="59" type="state" name="Washington">
<zindexValue>263,278</zindexValue>
<zindexOneYearChange>-0.066</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-home-value/r_59/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/WA/</forSaleByOwner>
<forSale>http://www.zillow.com/wa/</forSale>
</links>
</region>
</localRealEstate>
</result>
</results>
</response>
</SearchResults:searchresults>
Now the above type of XML is stored in variable named $zillow_data
First I load it using SimpleXML using the code
$xml = simplexml_load_string($zillow_data);
Now, I want to get the "message" value as shown in the XML data above.
When I try
foreach($xml->message[0]->text[0] as $response)
It does not work.
When I try something like the below code I get an error in Netbeans IDE
foreach($xml->SearchResults:searchresults[0]->message[0]->text[0] as $response)
The error I get is "unexpected : "
How do I correctly fetch the message in above XML data?
Also how do I parse through all the "result" elements, one by one?
If You use the code:
$xml = simplexml_load_string($string);
while the $string variable contains the XML, the first element <SearchResults:searchresults> becomes the main $xml SimpleXMLElement object, while the child tags <request>, <message> and <response> are its properties.
Thus, forgetting about the undefined namespace warnings, You should be able to do e.g.:
foreach($xml->response->results->result as $result) {
echo (string) $result->zpid;
}
There is only one message with only one text element, thus if You want to echo this one, You should only do:
echo (string) $xml->message->text;
Do a var_dump($xml); to understand the XML structure being transformed into objects and arrays after loading it with SimpleXML.
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