php - How to get the value of an array based on its name? -
i have xml info formatted so:
<additionalinformation> <item> <multiplevalues>0</multiplevalues> <name>some name here 1</name> <valuearray></valuearray> <value>123</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 2</name> <valuearray></valuearray> <value>abc</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 3</name> <valuearray></valuearray> <value>456</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 4</name> <valuearray></valuearray> <value>def</value> </item> </additionalinformation> i looping through info using:
foreach($listing->additionalinformation->item $item) { if ($item->name == 'some name here 3') { $val = ''; echo ''; } } how value of "some name here 3"?
i cannot utilize $item[3] since there various numbers of items.
this job xpath if inquire me (or kojiro), already, need output value:
... $val = $item->value; echo $val; ... using xpath spare iterate on elements query executed , gives more specific result already:
$name = 'some name here 3'; $query = sprintf('//item[name=%s]/value', xpath_string($name)); list($value) = $listing->xpath($query) + [null]; echo $value; the total example:
<?php /** * @link http://stackoverflow.com/questions/24370072/how-to-get-the-value-of-an-array-based-on-its-name */ $buffer = <<<xml <listing> <additionalinformation> <item> <multiplevalues>0</multiplevalues> <name>some name here 1</name> <valuearray></valuearray> <value>123</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 2</name> <valuearray></valuearray> <value>abc</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 3</name> <valuearray></valuearray> <value>456</value> </item> <item> <multiplevalues>0</multiplevalues> <name>some name here 4</name> <valuearray></valuearray> <value>def</value> </item> </additionalinformation> </listing> xml; /** * xpath string handling xpath 1.0 "quoting" * * @link http://hakre.wordpress.com/2013/07/11/mitigating-xpath-injection-attacks-in-php/ * * @param string $input * * @return string */ function xpath_string($input) { if (false === strpos($input, "'")) { homecoming "'$input'"; } if (false === strpos($input, '"')) { homecoming "\"$input\""; } homecoming "concat('" . strtr($input, array("'" => '\', "\'", \'')) . "')"; } $listing = simplexml_load_string($buffer); foreach ($listing->additionalinformation->item $item) { if ($item->name == 'some name here 3') { $val = $item->value; echo $val; } } $name = 'some name here 3'; $query = sprintf('//item[name=%s]/value', xpath_string($name)); list($value) = $listing->xpath($query) + [null]; echo $value; php xml
No comments:
Post a Comment