This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 8 years ago.
Greetings Everybody & thanks in advance for your answers.
So, my difficulty is this, i found a nice tutorial about a restful web service and i can not manage to modify it to my needs.
The below sample code works like a charm
function get_price($find) {
$products = array(
"test" => 293,
"test2" => 348,
"test3" => 267
);
foreach ($products as $product => $price) {
if ($product == $find) {
return $price;
break;
}}}
The $price return runs correctly for each of the above elements of the array which i choose through a simple html form.
Now my code
function get_tickets($find){
$xml = simplexml_load_file("products.xml");
// Here i want to return some of the xml's elements
}
and the included xml file
<products>
<company>
<name>test</name>
<tel>test</tel>
</company>
<products>
<product id="1">
<name>test</name>
<value>test</value>
<color>test</color>
</product>
</products>
</products>
I want to be able to access all the elements of the xml like the first sample code. Thank you.
The xpath() function should do want you want. It returns an array of elements that match the path given. For example, $xml->xpath("products/products/product") will give you all your product elements.
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 do you parse and process HTML/XML in PHP?
(31 answers)
Closed 6 years ago.
I have this HTML file items.php:
<all>
<designItems base="http://website.com/cms/items/">
<item price="20" contentId="10928" name="Designed by X091">
<hair set="10">
<data>
<![CDATA[
[{"c":110092,"y":10,"x":34}]
]]>
</data>
</hair>
</item>
<item price="90" contentId="10228" name="Designed by XXX">
<hair set="2">
<data>
<![CDATA[
[{"c":110022,"y":-2,"x":90}]
]]>
</data>
</hair>
</item>
</designItems>
</all>
In displayItems.php, I would like to use preg_match to find the item(s) that has/have the name="Designed by X091" and get it's price and contentId, and its hair set and the data.
With preg_match is it possible? Thanks :)
For this you do not want to use regular expressions, as the potential for erroneous parsing is too great. Instead you should use parsing library, like SimpleXML or similar.
Then you can use a simple loop, to check for the name attribute. Something like this, in other words:
$items = new SimpleXMLElement ($items);
// Loop through all of the elements, storing the ones we want in an array.
$wanted = array ();
foreach ($items->designItems->item as $current) {
// Skip the ones we're not interested in.
if ($current['title'] != 'designed by aaaa') {
continue;
}
// Do whatever you want with the item here.
}
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 answers here:
How to retrieve data from # xml attribute in PHP
(2 answers)
Closed 8 years ago.
I saw lot of examples but nothing is working perfectly. This is the array i got after parsing.
SimpleXMLElement Object
(
[#attributes] => Array
(
[areaUnits] => acre
)
)
Now i try to get attributes,like this:
var_dump($list->attributes());
I got this error:
var_dump(): Node no longer exists
<?php
function xml_attribute($object, $attribute)
{
if(isset($object[$attribute]))
return (string) $object[$attribute];
}
print xml_attribute($xml, 'areaUnits'); //prints "acre"
?>
Obtaining the attributes of a SimpleXMLElement is very straight forward.
The XML:
<?xml version="1.0"?>
<root>
<node attribute1="value1" attribute2="value2">data</node>
</root>
The PHP:
// assume $xml variable contains the XML document above
$sxe = new SimpleXMLElement($xml)
$value1 = $sxe->node->attributes()->attribute1;
$value2 = $sxe->node->attributes()->attribute2;
In your example above, $list MUST reference an actual XML node in order for you to attempt to access its attributes. Based on your error, it sounds like you're not doing that, which can often happen if you modify the XML structure referenced by $list at run time.
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