如何读取保存在文本文件中的数据数组并使用 PHP 循环遍历它们?
How to read a data-array saved in a text file and loop through them with PHP?
这个值
//myfile.txt
data:[
{'name': 'Item 1', 'icon': 'snowplow', 'inv': 'B123', 'eh': 'h'},
{'name': 'Item 2', 'icon': 'snowplow', 'inv': 'B456', 'eh': 'h'},
{'name': 'Item 3', 'icon': 'snowplow', 'inv': 'B789', 'eh': 'h'},
{'name': 'Item 4', 'icon': 'snowplow', 'inv': 'B102', 'eh': 'h'}
]
存储在我无法更改的 *.txt 文件中。如果我像这样用 PHP 阅读这个文本文件:
$fn = fopen("myfile.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
// echo $result[name];
// echo $result[icon];
// echo $result[inv];
// echo $result[eh];
}
fclose($fn);
如何使用 PHP 遍历这些值?
正如所指出的那样,如果源数据被正确格式化为已知数据类型,例如 JSON 甚至 XML
要捏造上述数据以便更容易解析,您需要删除 data:
并将单引号更改为双引号,然后再像往常一样继续。应该注意的是,这有点老套....
/*
replace the single quotes for double quotes
then split the resulting string using `data:` as the delimiter
and then convert to JSON
*/
list( $junk, $data )=explode( 'data:', str_replace( "'", '"', file_get_contents('myfile.txt') ) );
$json=json_decode( $data );
foreach( $json as $obj ){
/*
to get an unknown, potentially large, number of items from each object within data structure
you can iterate through the keys of the sub-object like this.
*/
$keys=array_keys( get_object_vars( $obj ) );
$tmp='';
foreach( $keys as $key )$tmp.=sprintf( '%s=%s, ', $key, $obj->$key );
printf('<div>%s</div>', $tmp );
/* Or, with known items like this: */
echo $obj->name . ' ' . $obj->icon . '/* etc */<br />';
}
这个值
//myfile.txt
data:[
{'name': 'Item 1', 'icon': 'snowplow', 'inv': 'B123', 'eh': 'h'},
{'name': 'Item 2', 'icon': 'snowplow', 'inv': 'B456', 'eh': 'h'},
{'name': 'Item 3', 'icon': 'snowplow', 'inv': 'B789', 'eh': 'h'},
{'name': 'Item 4', 'icon': 'snowplow', 'inv': 'B102', 'eh': 'h'}
]
存储在我无法更改的 *.txt 文件中。如果我像这样用 PHP 阅读这个文本文件:
$fn = fopen("myfile.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
// echo $result[name];
// echo $result[icon];
// echo $result[inv];
// echo $result[eh];
}
fclose($fn);
如何使用 PHP 遍历这些值?
正如所指出的那样,如果源数据被正确格式化为已知数据类型,例如 JSON 甚至 XML
要捏造上述数据以便更容易解析,您需要删除 data:
并将单引号更改为双引号,然后再像往常一样继续。应该注意的是,这有点老套....
/*
replace the single quotes for double quotes
then split the resulting string using `data:` as the delimiter
and then convert to JSON
*/
list( $junk, $data )=explode( 'data:', str_replace( "'", '"', file_get_contents('myfile.txt') ) );
$json=json_decode( $data );
foreach( $json as $obj ){
/*
to get an unknown, potentially large, number of items from each object within data structure
you can iterate through the keys of the sub-object like this.
*/
$keys=array_keys( get_object_vars( $obj ) );
$tmp='';
foreach( $keys as $key )$tmp.=sprintf( '%s=%s, ', $key, $obj->$key );
printf('<div>%s</div>', $tmp );
/* Or, with known items like this: */
echo $obj->name . ' ' . $obj->icon . '/* etc */<br />';
}